
TVB.util.namespace("TVB.Pdes");

TVB.Pdes.Mod = {

    /*------------------- Global Method shared for modules -----------------*/
    getFolderItems: function (container) {    //called by red
        var url = TVB.Pdes.Config.URL.GET_FOLDER_ITEMS,
            fvars = $(container).parent().find('.fvars').val(),
            o = eval('(' + fvars + ')'),
            ptype = o.ptype,
            ftype = o.ftype,
            id = o.fid,
            oParam = TVB.Pdes.oParam;
        if(!$(container).hasClass("cms-jqgrid")){
            $.get(url, {'ptype':ptype, 'id':id, 'ftype':ftype, 'format':'html'}, function (data) {
                if (data !== '') {
                    container.innerHTML = '<ul class="ui-widget-content">' + data + '</ul>';
                } else {
                    container.innerHTML = '';
                }
            }, 'html');
        }else{
            url += (url.match(/\?/) ? "&" : "?") + "id=" + id + "&ptype=" + ptype + "&ftype=" + ftype + "&format=jqgrid"; 
            url += '&act=' + oParam.act;
            if (typeof oParam.unpublish !== 'undefined') {
                url += '&unpublish=' + oParam.unpublish;
            }
            if (typeof oParam.premium !== 'undefined') {
                url += '&premium=' + oParam.premium;
            }
            var tbl, pager;
            if($(".ui-jqgrid",container).length==0){
                tbl = $("table.scroll",container).attr("id","jg_tbl_f_"+ftype+"_"+id);
                pager = $("div.scroll",container).attr("id","jg_pgr_f_"+ftype+"_"+id);
                tbl.jqGrid({
                    url : url,
                    datatype : 'json',
                    rowNum : '5',
                    rowList : [5,10,20],
                    viewrecords : true,
                    height : 'auto',
                    sortname : 'id',
                    sortorder : 'desc',
                    pager : pager,
                    colNames : ['ID','Title','Modified at','Modified by','Status','Action Buttons'],
                    colModel : [
                        {name:'id',index:'id',width:'65'},
                        {name:'title',index:'title',width:'250'},
                        {name:'modified_at',index:'modified_at',width:'145'},
                        {name:'modified_by',index:'modified_by',width:'100'},
                        {name:'status',index:'status',width:'100'},
                        {name:'op',index:'op',sortable:false,width:'250'}
                    ],
                    loadComplete : function (){
                        var m;
                        $("a.btn.view,a.btn.edit",this).unbind("click").bind("click", function (){ 
                            if((oParam.act=='edit') && (m = $(this).attr("href").match(/(edit|view)\-(\d+)/))){    
                                if (confirm(TVB.Pdes.Config.TXT.SAVE_EXIST_DATA)) {
                                    $("input[name=folder_video_act]").val(m[1]);
                                    $("input[name=folder_video_id]").val(m[2]);
                                    document.ane.submit();
                                }else{
                                    $("input[name=folder_video_act]").val('');
                                    $("input[name=folder_video_id]").val('');
                                }
                                return false;
                            }                            
                        });
                    }
                }).navGrid(pager,{edit:false,add:false,del:false});
            }else{
                tbl = $("#jg_tbl_f_"+ftype+"_"+id, container);
                tbl.jqGrid().trigger('reloadGrid');
            }            
            
        }        
    },
    saveUrlInSession: function () {
        window.name = location.href;	
    },
    getUrlInSession: function () {
        return window.name;	
    },

    /*---------- Static Initialization function for modules or components -------------*/
    initCreateProgramme: function () {
        $("select[name='cpl_company_code']").bind("change", function(){
            if(!this.value || this.value == '0'){
                $("#cpl_id").removeClass("error");
                $("#cpl_id")[0].disabled = true;
                $("#cpl_id")[0].value = '';
                $(".grid-r label[for='cpl_id']").hide();
                $(".grid-l label[for='cpl_id'] ins").remove();
                TVB.Pdes.oValidation.rules.cpl_id.required = false;
                
                $("#effective_date").removeClass("error");
                $("#effective_date")[0].disabled = true;
                $("#effective_date")[0].value = '';
                $(".grid-r label[for='effective_date']").hide();
                $(".grid-l label[for='effective_date'] ins").remove();
                TVB.Pdes.oValidation.rules.effective_date.required = false;
            }else{
                $("#cpl_id")[0].disabled = false;
                if($(".grid-l label[for='cpl_id'] ins").length == 0){
                    $(".grid-l label[for='cpl_id']").prepend('<ins title="mandatory field">*</ins>');
                }
                TVB.Pdes.oValidation.rules.cpl_id.required = true;
                
                $("#effective_date")[0].disabled = false;
                if($(".grid-l label[for='effective_date'] ins").length == 0){
                    $(".grid-l label[for='effective_date']").prepend('<ins title="mandatory field">*</ins>');
                }
                TVB.Pdes.oValidation.rules.effective_date.required = true;
            }
        });
        
    },
    initAddCpl: function () {
        $('form .addcpl').bind("click", function (e) {
            var values = [],
                validation = 0,
                html = [],
                oUl,
                obj;
            
			var checkdata = function (val)
			{
				var b = false;			
				for(var i=0;i<oUl.children().length;i++)
				{	
					 var tmpObj = oUl.children().get(i);
					if($(tmpObj).find('input').eq(0).val()==obj.code && $(tmpObj).find('input').eq(1).val()==obj.id)
					{
						alert(TVB.Pdes.Config.TXT.EQUIVALENT_PROG_EXIST);
						return true;
					}else if($(tmpObj).find('input').eq(2).val()==obj.date)
					{
						alert(TVB.Pdes.Config.TXT.EQUIVALENT_PROG_DATE_EXIST);
						return true;	
					}
									
				}
				return b;
			};
			
            $(this).closest('.cpl table').find('.field').each(function (i) {
                var v = $(this).val();
                if (v === '') {
                    validation += 1;
                } /*else if (i == 1 && !v.match(/^\d+$/) ) {
                    validation = 100;
                }*/
                values.push(v);
            });
            if (validation === 0) {
                oUl = $(this).closest('.cpl table').prev('ul');
                html[html.length] = '<li>';
                html[html.length] = values[0] + '<input type="hidden" name="cpl_company_code[]" value="' + values[0] + '" /> ';
                html[html.length] = TVB.util.toHtmlEntities($.trim(values[1])) + '<input type="hidden" name="cpl_id[]" value="' + encodeURIComponent($.trim(values[1])) + '" /> ';
                html[html.length] = values[2] + '<input type="hidden" name="effective_date[]" value="' + values[2] + '" /> ';
                html[html.length] = '<a class="btn-del" href="">del</a></li>';
				obj = {'code':values[0],'id':$.trim(values[1]),'date':values[2]};
               if(!checkdata(obj)) {
               	   oUl.append(html.join(''));
				   $(oUl.next().find('.field').eq(1)).val('').focus();
				} else {
				  // alert(TVB.Pdes.Config.TXT.EQUIVALENT_PROG_EXIST);
				}
            } else {
                alert(validation > 99 ? TVB.Pdes.Config.TXT.INVALID_PROG_NO_FORMAT : TVB.Pdes.Config.TXT.PLEASE_FILL_ALL_TEXTFIELD);
            }
			
        });
        $('.cpl li .btn-del').live('click', function (e){
            e.preventDefault();
            $(this).closest('li').remove();
        });
    },

    initMamAutoFill: function () {
        var joCompanyCode = $('#programme-step1 select[name="cpl_company_code"]');
        var joCplId = $('#cpl_id');
        var joCplCatId = $('#cpl_category_id');
        var joTitle = $('#programme-step1 input[name="title"]');
        var joTitleEn = $('#title_en');
        joCompanyCode.bind('change', function (e) {
            joCplId.val('');
        });
        joCplId.bind('blur', function (e) {
            var ajaxApi = TVB.Pdes.Config.URL.GET_CPL_INFO;
            var autoFill = function (result) {
                var data = result.data;
                if (result.status < 300) {
                    joTitle.val(data.title);
                    joTitleEn.val(data.title_en);
                    joCplCatId.val(data.cpl_category_id);
                } else {
                    joTitle.val('');
                    joTitleEn.val('');
                    joCplCatId.val('');
                }
            };
            $.get(ajaxApi, {'company_code': joCompanyCode.val(), 'cpl_id': joCplId.val()}, autoFill, 'json');
        });
    },

    initRedCallers: function () {        
        var thisMovie = function (swf) {
            if(navigator.appName.indexOf("Microsoft") != -1) {
                return window[swf];
            }else{ 
                return document[swf]; 
            }
        };
        var sendEvent = function (swf,typ,prm){
            thisMovie(swf).sendEvent(typ,prm);
        };
        var loadFile = function (swf,obj) {
            var movie = thisMovie(swf);
            movie.loadFile(obj);
            //thisMovie(swf).loadFile(obj);
        };
        var loadVideo = function (theFile, theThumb) {
            if (theThumb) {
                loadFile('mpl',{"file":theFile,"image":theThumb});
            }else{
                loadFile('mpl',{file:theFile});
            }
            sendEvent('mpl','playpause');
        };
        var initPlayer = function (url, file, thumb) {
            var width = "420";
            var height= "260";
            var so = new SWFObject('swf/mediaplayer.swf','mpl',width,height,'8');
            so.addParam('allowscriptaccess','always');
            so.addParam('allowfullscreen','true');
            so.addParam('wmode','opaque');
            so.addVariable('height',height);
            so.addVariable('width',width);
            so.addVariable('overstretch','fit');
            so.addVariable('shuffle','false');
            so.addVariable('enablejs','true');
            so.addVariable("autostart","true");
            so.addVariable('searchbar', 'false');
            so.addVariable("file", url);
            so.addVariable('id', file);
            so.addVariable("image", thumb);
            so.write('player');
        };

        var oPopPlayer = null;
        $('div.red-callers a.preview').live("click", function (e) {
            var src = this.href,
                title, thumb, arrSrc;
            if ($(this).hasClass('video')) {
                e.preventDefault();
                if (src != window.location) {
                    if (oPopPlayer === null) {
                        oPopPlayer = $("#pop-player").dialog({
                            bgiframe: true,
                            resizable: false,
                            width: 450,
                            autoOpen: false,
                            modal: true,
                            beforeclose: function () {
                                sendEvent('mpl','playpause');
                            }
                        });
                    }
                    title = $(this).next('p').attr('title');
                    thumb = $(this).find('img').attr('src');
                    arrSrc = src.split('*');
                    if (arrSrc.length === 1) {
                        arrSrc[1] = '';
                    }
                    oPopPlayer.dialog('option', 'title', title);
                    oPopPlayer.dialog('open');
                    initPlayer(arrSrc[0], arrSrc[1], thumb);
                }
            }
        });

        //Chapter Marking Entrance in the video list
        $('form div.red-callers a.chapter-marking').live('click', function (e) {
            e.preventDefault();
            var elForm = document.ane,
                vid = this.href.split("#")[1],
                url = elForm.action,
                oParam = TVB.Pdes.oParam;
            if (oParam.act && oParam.act !== 'view') {
                if (confirm(TVB.Pdes.Config.TXT.SAVE_EXIST_DATA)) {
                    url += (url.match(/\?/) ? "&" : "?") + "vid=" + vid;
                    elForm.action = url;
                    elForm.submit();
                }
            } else {
                url = TVB.Pdes.Config.URL.VIEW_CHAPTER_MARKING;
                url += (url.match(/\?/) ? "&" : "?") + 'id=' + vid;
                if (typeof oParam.unpublish !== 'undefined') {
                    url += '&unpublish=' + oParam.unpublish;
                }
                if (typeof oParam.premium !== 'undefined') {
                    url += '&premium=' + oParam.premium;
                }
                $.iframe_dialog(url, {width:1020, title:'Chapter Marking'});
            }
        });
        
        $('div.red-callers .cms-jqgrid').each(function (i, el){
            TVB.Pdes.Mod.getFolderItems(el);
        });

    },

    initChapterMarking: function () {
        var oSelectedInfo = null,
            strSelectedInfo = '',
            oInfoNames = null,
            oInfoPreviewUrl = null,
            arrInfoDbType = ['address','recipe','song','biography','award','product','qa','general_info','pageant'],
            arrInfoUiType = ['Address','Recipe','Song','Biography','Award','Product','Q&A','General Info','Pageant'],
            $episodeId = $('#chapter-marking input[name="episode_id"]');

        var iNewChapter = 0,
            chapterTemplate = $('#chapter_modal').clone().attr('id', '').removeClass('template');
        $('#chapter_modal').remove();
        if ($episodeId.val() === '') {
            chapterTemplate.find('input.attach_info_type').css('display','none');
        }


        var populateInfoList = function () {
            var arr,
                html = [],
                str = '',
                uType = '',
                dType,
                container = $('#infotype_attach_target').next('div').find('div.info-list');
            
            for (dType in oSelectedInfo) {
                if (oSelectedInfo.hasOwnProperty(dType)) {
                    arr = oSelectedInfo[dType];
                    uType = arrInfoUiType[$.inArray(dType, arrInfoDbType)];
                    for (var i = 0; i < arr.length; i += 1) {
                        html[html.length] = '<li><span class="type">' + uType + '</span> - <span class="name">' + oInfoNames[dType + arr[i]] + '</span><a href="' + oInfoPreviewUrl[dType + arr[i]] + '" class="infotype_details ui-icon ui-icon-search"/><a href="#' + arr[i] + '" class="btn-del">del</a></li>';
                    }
                }
            }
            
            str = (html.length === 0) ? '' : '<ul class="ui-widget-content">' + html.join('') + '</ul>';
            container.html(str);
            oInfoNames = null;
            oInfoPreviewUrl = null;
        };

        $("#chapter-marking .info-list .btn-del").live("click", function (e) {
            e.preventDefault();
            var id = $(this).attr('href').replace(/#/, '');
            var uType = $(this).parent().children('.type').text();
            var elHidden = $(this).closest('fieldset').find('input[name="attached_info[]"]');
            var dType = arrInfoDbType[$.inArray(uType, arrInfoUiType)];
            strSelectedInfo = elHidden.val();
            oSelectedInfo = eval('(' + strSelectedInfo + ')');
            TVB.util.arrReduce(oSelectedInfo[dType], id);
            elHidden.val(JSON.stringify(oSelectedInfo)).removeAttr('id');
            oSelectedInfo = null;
            $(this).parent().remove();
        });

    	$('#infotype_search').dialog({
    		title: 'Find info type',
    		width: 500,
    		modal: true,
    		height: 650,
    		autoOpen: false,
    		buttons: {
    			'Select': function () {
                    populateInfoList();
                    $('#infotype_attach_target').val(JSON.stringify(oSelectedInfo)).removeAttr('id');
                    oSelectedInfo = null;
    				$(this).dialog("close");
    			}
    		}
    	});
    	$('input.attach_info_type').live('click', function () {
    		$(this).closest('fieldset').find('input[name="attached_info[]"]').attr('id', 'infotype_attach_target');
            strSelectedInfo = $('#infotype_attach_target').val();
            oSelectedInfo = strSelectedInfo === '' ? {} : eval('(' + strSelectedInfo + ')');
            oInfoNames = {};
            oInfoPreviewUrl = {};
            $(this).prev('div.info-list').find('li').each(function (i) {
                var uType = $('.type', this).text(),
                    name = $('.name', this).html(),
                    previewUrl = $('.infotype_details', this).attr('href'),
                    id = $('a.btn-del', this).attr('href').replace(/#/, ''),
                    dType = arrInfoDbType[$.inArray(uType, arrInfoUiType)];
                oInfoNames[dType + id] = name;
                oInfoPreviewUrl[dType + id] = previewUrl;
            });
            $('select[name="infotype"]').trigger("change");
    		$('#infotype_search .results').html("Pick an info type to search");
    		$('#infotype_search').dialog("open");
    	});

        $('#infotype_search .results input[type="checkbox"]').live('click', function (e) {
            var arr = this.value.split(':');
            var name = $(this).parent().children('p').html();
            var previewUrl = $(this).parent().children('a').attr('href');
            if (this.checked) {
                if (!$.isArray(oSelectedInfo[arr[0]])) {
                    oSelectedInfo[arr[0]] = [];                
                }
                oSelectedInfo[arr[0]].push(arr[1]);
                oInfoNames[arr[0] + arr[1]] = name;
                oInfoPreviewUrl[arr[0] + arr[1]] = previewUrl;
            } else {
                TVB.util.arrReduce(oSelectedInfo[arr[0]], arr[1]);
                delete oInfoNames[arr[0] + arr[1]];
                delete oInfoPreviewUrl[arr[0] + arr[1]];
            }
        });

    	$('select[name="infotype"]').change(function () {
            if (this.value !== '0') {
        		var result_div = $('#infotype_search').find('div.results');
        		var form = $('form[name="find_infotype"]');
        		result_div.html('loading...');
                var o = this.value === 'all' ? oSelectedInfo : oSelectedInfo[this.value];
                var value = o === null ? '' : JSON.stringify(o);
                $('input[name="selected"]', form).val(value);
        		$.ajax({
        			url: form.attr('action'),
                    type: 'POST',
        			data: form.serialize(),
        			success: function (data) {
        				result_div.html(data);
        			}
        		});
            }
    	});

    	$('a.infotype_details').live('click', function () {
    		$.iframe_dialog($(this).attr('href'), {width:1020, title:'Info Details'});
    		return false;
    	});
    	$('#chapter-marking .close').live('click', function (e) {
            e.preventDefault();
            var hiddenField,
                arr,
                value,
                chapterId = $(this).parent().find('input[name="chapter_id[]"]').val();
            if (!chapterId.match(/new/)) {
                hiddenField = $(this).closest('form').find('input[name="deleted_chapters"]');
                value = hiddenField.val();
                arr = value === '' ? [] : value.split(',');
                arr.push(chapterId);
                hiddenField.val(arr.join(','));
            }
            $(this).parent().remove();
    	});

        /* For IntTime OutTime */

        var time2seconds = function (time) {
            var arr = typeof time === 'string' ? time.split(':') : time;
            return parseInt(arr[0],10)*60*60 + parseInt(arr[1],10)*60 + parseInt(arr[2],10);
        };
        var seconds2time = function (seconds) {
            var arr = [];
            arr[0] = Math.floor(seconds/3600);
            arr[1] = Math.floor((seconds - arr[0]*3600)/60);
            arr[2] = seconds%60;
            for (var i = 0, len = arr.length; i < len; i += 1) {
                if (arr[i] < 10) {
                    arr[i] = '0' + arr[i];
                }
            }
            return arr.join(':');
        };
        var fillInOutTime = function (inTime, outTime, chapter) {
            var arrOutTime = outTime.split(':');
            var arrInTime = inTime.split(':');
            $('input[name^="chapter_in_time_"]', chapter).each(function (i) {
                this.value = arrInTime[i];
            });
            $('input[name^="chapter_out_time_"]', chapter).each(function (i) {
                this.value = arrOutTime[i];
            });
        };
        var getPrevOutTime = function (chapter) {
            var arrOutTime = [];
            $('input[name^="chapter_out_time_"]', chapter).each(function (i) {
                if (this.value === '') {
                    this.value = '00';
                }
                arrOutTime.push(this.value);
            });
            return arrOutTime.join(':');
        };
        var nDuration = time2seconds( $('input.duration').val() );
        var validateInOutTime = function () {
            var arrIn = [];
            var oOut = {};
            var b = true;
            $('fieldset.chapter', '#chapter-marking').each(function () {
                var nInTime, nOutTime, arrInTime = [], arrOutTime = [];
                $('input[name^="chapter_in_time_"]' ,this).each(function () {
                    if (this.value === '') {
                        this.value = '00';
                    }
                    arrInTime.push(this.value);
                });
                $('input[name^="chapter_out_time_"]' ,this).each(function () {
                    if (this.value === '') {
                        this.value = '00';
                    }
                    arrOutTime.push(this.value);
                });
                nInTime = time2seconds(arrInTime);
                nOutTime = time2seconds(arrOutTime);
                if (nInTime >= nOutTime) {
                    alert(TVB.Pdes.Config.TXT.OUTTIME_GT_INTIME);
                    b = false;
                    return;
                }
                if (nOutTime > nDuration) {
                    alert(TVB.Pdes.Config.TXT.OUTTIME_NOTGT_DURATION);
                    b = false;
                    return;
                }
                if ($.inArray(nInTime, arrIn) === -1) {
                    arrIn.push(nInTime);
                    oOut['t' + nInTime] = nOutTime;                
                } else {
                    alert(TVB.Pdes.Config.TXT.OUTTIME_INTIME_OVERLAPPED);
                    b = false;
                    return;
                }
            });

            if (b) {
                arrIn.sort(function (a, b) {
                    return a - b;
                });
                for (var i = 1, len = arrIn.length; i < len; i += 1) {
                    if (arrIn[i] <= oOut['t' + arrIn[i - 1]]) {
                        alert(TVB.Pdes.Config.TXT.OUTTIME_INTIME_OVERLAPPED);
                        b = false;
                        break;
                    }
                }
            }
            return b;
        };

    	$('#add-chapter').click(function () {
            var length = $('fieldset.chapter').length,
                prevChapter,
                inTime,
                outTime = seconds2time(nDuration),
                prevInTime,
                prevOutTime;
            if ( length === 0) {
                inTime = '00:00:00';
            } else {
                prevChapter = $('#chapter-marking fieldset.chapter').get(length - 1);
                prevOutTime = getPrevOutTime(prevChapter);
                if (time2seconds(prevOutTime) >= nDuration) {
                    inTime = outTime;
                } else {
                    inTime = seconds2time( time2seconds(prevOutTime) + 1 );
                }
            }
            var newChapter = chapterTemplate.clone().insertBefore('#chapter_placeholder');
            $('input[name="chapter_id[]"]', newChapter).val('new' + iNewChapter);
            TVB.Cms.uiInit(newChapter);
            TVB.Pdes.Mod.initEditableListAutoComplete(newChapter);    //init autocomplete while adding a new chapter
            iNewChapter += 1;
            fillInOutTime(inTime, outTime, newChapter);
    	});

        /** commented this validation for old data.
        $('#chapter-marking form').submit(function (e) {
            if ( !(validateInOutTime()) ) {
                e.preventDefault();
            }
        });
        */

        if (nDuration === 0) {    // the length of VD is zero
            $('#add-chapter').parent().css('display', 'none');
        } else if ($('#chapter-marking fieldset.chapter').length === 0) {    // have no chapter
            $('#add-chapter').trigger('click');    // add a chapter by default
        }

    },

    initChangeVd: function () {
        var $popVideoList = null,
            $btnDownload = $('#player-wrapper a.download'),
            $newVideoId = $('#chapter-marking input[name="new_video_id"]');

        var initPlayer = function (url, file, thumb) {
            var width = "385";
            var height= "240";
            var so = new SWFObject('swf/mediaplayer.swf','mpl',width,height,'8');
            so.addParam('allowscriptaccess','always');
            so.addParam('allowfullscreen','true');
            so.addParam('wmode','opaque');
            so.addVariable('height',height);
            so.addVariable('width',width);
            so.addVariable('overstretch','fit');
            so.addVariable('shuffle','false');
            so.addVariable('enablejs','true');
            so.addVariable("autostart","false");
            so.addVariable('searchbar', 'false');
            so.addVariable("file", url);
            so.addVariable('id', file);
            so.addVariable("image", thumb);
            so.write('player');
        };

        $('#player-wrapper a.change-vd').click(function (e) {
            e.preventDefault();
            if (!confirm(TVB.Pdes.Config.TXT.CONFIRM_CHANGE_VD)) {
                return;
            }
            var url = TVB.Pdes.Config.URL.GET_VIDEOS,
                episodeId = $('#chapter-marking input[name="episode_id"]').val(),
                $container = $('#pop-videolist div.bd ul');
            if ($popVideoList === null) {
                $popVideoList = $("#pop-videolist").dialog({
                    bgiframe: true,
                    resizable: false,
                    width: 680,
                    autoOpen: false,
                    modal: true,
                    title: 'Change Video'
                });
            }
            $container.html('');
            $popVideoList.dialog('open');
            $.get(url, {'episode_id': episodeId, 'format':'html'}, function (data) {
                $container.html(data);
            }, 'html');
        });     
        $("#pop-videolist .select").live('click', function (e) {
            var arrSrc, thumb, id, downloadUrl;
            e.preventDefault();
            if (this.href !== '') {
                arrSrc = this.href.split('*');
                thumb = $(this).find('img').attr('src');
                id = $(this).parent().children('input[name="id"]').val();
                downloadUrl = $(this).parent().children('input[name="download_url"]').val();
                if (arrSrc.length === 1) {
                    arrSrc[1] = '';
                }
                initPlayer(arrSrc[0], arrSrc[1], thumb);
                $newVideoId.val(id);
                $btnDownload.attr('href', downloadUrl);
                $popVideoList.dialog('close');
                $('#chapter-marking form').unbind().submit();    //disable FE validation and submit the form.
            }
        });
        $("#pop-videolist .close").click(function (e) {
            $popVideoList.dialog('close');
        });
    },

    initGlobalNameInput: function () {

        var updateSorting = function (tbody) {
            var j = $(tbody).find('tr').length;
            $(tbody).find('tr').each(function (i, el) {
                var rowClass = '';
                if (i === 0 && j === 1) {
                    rowClass = 'fst lst';
                } else if (i === 0 && i < j) {
                    rowClass = 'fst';
                } else if (i === j - 1) {
                    rowClass = 'lst';
                }
                this.className = rowClass;

                $('*[name]', this).each(function (j, el) {
                    el.name = el.name.replace(/(\[\d*\])$/g, function (m, key, value) {
                        return '['+ i + ']';
                    });
                });
            });
        };

        $('.global-name .up').live('click', function (e){
            e.preventDefault();
            var tbody = $(this).closest('tbody'),
                thisRow = $(this).closest('tr'),
                prevRow = $(thisRow).prev('tr');
            thisRow.insertBefore(prevRow);
            updateSorting(tbody);
        });

        $('.global-name .down').live('click', function (e){
            e.preventDefault();
            var tbody = $(this).closest('tbody'),
                thisRow = $(this).closest('tr'),
                nextRow = $(thisRow).next('tr');
            thisRow.insertAfter(nextRow);
            updateSorting(tbody);
        });

        $('.global-name .add').live('click', function (e){
            e.preventDefault();
            var table = $(this).prev('table');
            var tbody = $(table).find('tbody');
            var template = $(this).next('.template').val();
            template = decodeURI(template);
            tbody.append(template);
            updateSorting(tbody);
        });

        $('.global-name .del').live('click', function (e){
            e.preventDefault();
            var tbody = $(this).closest('tbody');
            $(this).closest('tr').remove();
            updateSorting(tbody);
        });

        $('.global-name .detail').live('click', function (e){
            var castId = $(this).prev('input').val(),
                elTr,nameType,lastName,firstName,alphabet,roleId,elForm,url;
            e.preventDefault();
            if (TVB.Pdes.oParam.act && TVB.Pdes.oParam.act !== 'view') {
                elTr = $(this).closest('tr');
                nameType = $('.name-type', elTr).val();
                lastName = encodeURIComponent($('.last .cast-name', elTr).val());
                firstName = encodeURIComponent($('.first .cast-name', elTr).val());
                alphabet = $('input.alphabet_data', elTr).val();
                roleId = $('.role-id', elTr).val();
                elForm = document.ane;
                url = elForm.action;
                if (lastName === '' && firstName === '') {
                    alert(TVB.Pdes.Config.TXT.PLEASE_INPUT_NAME);
                    return;
                }
                if (confirm(TVB.Pdes.Config.TXT.SAVE_EXIST_DATA)) {
                    if (castId === '') {
                        castId = -1;
                    }
                    url += (url.match(/\?/) ? "&" : "?") + 'param_role_id=' + roleId + '&param_cast_id=' + castId + '&param_name_type=' + nameType + '&param_last_name=' + lastName + '&param_first_name=' + firstName + '&param_alphabet=' + alphabet;
                    elForm.action = url;
                    elForm.submit();
                }
            } else {
                url = TVB.Pdes.Config.URL.VIEW_CAST;
                url += (url.match(/\?/) ? "&" : "?") + 'id=' + castId;
                $.iframe_dialog(url, {width:1020, title:'Cast Details'});
            }
        });

        $('.global-name input.alphabet').live('change', function (e){
            var elTd = $(this).parent().next().next();
            $(this).next('input').val(this.checked ? '1' : '0');
            elTd.toggleClass('en', !this.checked);
        });

        $('.global-name select.name-type').live('change', function (e){
            e.preventDefault();
            var value = $(this).val();
            var b = (value > 10) ? true : false;
            var td = $(this).parent('td').next('td');
            td.toggleClass('single', b);
            td.find('.cast-name').val('');
        });
    },

    initEditableList: function () {

        var oPopList = null;
        var oPopCast = null;
        var oUl = null;
        var popType = '';
        var key, elId;
        var arrId = [];

        var map = {
            'Programme Category': {field:'category_id[]', ajax:1, max:Infinity},
            'tvb.com_cat': {field:'tvbcom_cat_id{key}[]', ajax:1, max:Infinity},
            'Programme Types': {field:'tag[1]{key}[]', ajax:1, max:Infinity},
            'tag': {field:'tag[1]{key}[]', ajax:1, max:Infinity},
            'programme_nature': {field:'tag[2]{key}[]', ajax:1, max:Infinity},
            'chapter_nature': {field:'tag[3]{key}[]', ajax:1, max:Infinity},
            'liberal_tag': {field:'tag[4]{key}[]', ajax:1, max:Infinity},
            'source': {field:'tag[5]{key}[]', ajax:1, max:Infinity},
            'seo': {field:'tag[13][]', ajax:1, max:15},
            'cast': {field:'cast_dict_id{key}[]', ajax:1, max:Infinity}
        };

        var updateListItem = function (oUl) {
            //update index for Back-end
            $('input[type="hidden"]',oUl).each(function(i){
                var name = $(this).attr('name').replace(/\[\d*\](\[new\]){0,1}$/, '[' + i + ']' + '$1');
                $(this).attr("name", name);
            });
            //update "up" and "down" arrow
            $('.btn-up, .btn-dn', oUl).css({"visibility":"visible"});
            $('li:first .btn-up, li:last .btn-dn', oUl).css({"visibility":"hidden"});
        };

        $('form .editable-list .addpop').live("click", function (e) {
            e.preventDefault();
            var populate, content;
            var ajaxApi = this.href;
            if (oPopList === null) {
                oPopList = $("#pop-list").dialog({
                    bgiframe: true,
                    resizable: false,
                    width: 600,
                    autoOpen: false,
                    modal: true
                });
            }

            //prepare selected id
            arrId = [];
            $(this).parent().find('li input[type="hidden"]').each(function () {
                arrId.push(this.value);
            });

            //for multi-group of tags
            key = '';
            elId = $(this).closest('fieldset').find('input[name="chapter_id[]"]');
            if (elId.length > 0) {
                key = elId.val();
            }
            if (key !== '') {
                key = '[' + key + ']';
            }

            oUl = $(this).parent().children('ul');
            popType = $(this).parent().children('.type').val();
            $("#pop-list div.bd").html('');
            oPopList.dialog('option', 'title', 'Add ' + popType);
            oPopList.dialog('open');

            populate = function (data) {
                var html = [];
                html[html.length] = '<ul>';
                for (var i = 0; i < data.length; i += 1) {
                    html[html.length] = '<li>';
                    if (popType === 'Programme Category' || popType === 'TVB.COM Category') {
                        html[html.length] = '<h4>' + data[i].name + '</h4>';
                    } else {
                        html[html.length] = '<a href="#' + data[i].id + '">' + data[i].name + '</a>';
                    }                
                    if (typeof data[i].child !== 'undefined' && data[i].child.length > 0) {
                        html[html.length] = '<ul class="sub">';
                        for (var j = 0; j < data[i].child.length; j += 1) {
                            html[html.length] = '<li>';
                            if (popType === 'Programme Category' || popType === 'TVB.COM Category') {
                                if (typeof data[i].child[j].child !== 'undefined' && data[i].child[j].child.length > 0) {
                                    html[html.length] = '<h4>' + data[i].child[j].name + '</h4>';
                                    html[html.length] = '<ul class="sub">';
                                    for (var k = 0; k < data[i].child[j].child.length; k += 1) {
                                        html[html.length] = '<li>';  
                                        html[html.length] = '<a href="#' + data[i].child[j].child[k].id + '">' + data[i].child[j].child[k].name + '</a>';
                                        html[html.length] = '</li>';   
                                    }
                                    html[html.length] = '</ul>';
                                } else {
                                    html[html.length] = '<a href="#' + data[i].child[j].id + '">' + data[i].child[j].name + '</a>';
                                }
                            } else {
                                html[html.length] = '<a href="#' + data[i].child[j].id + '">' + data[i].child[j].name + '</a>';
                            }
                            html[html.length] = '</li>';   
                        }
                        html[html.length] = '</ul>';
                    }
                    html[html.length] = '</li>';                   
                }
                html[html.length] = '</ul>';
                $("#pop-list div.bd").html(html.join(''));
                
                $("#pop-list .bd a").unbind("click").bind("click", function (e) {
                    var catId;
                    var field = map[popType].field;
                    var pCate = $(this).parent().parent();
        			var pName = "";
        			var tmpLi = "";
        			field = TVB.util.supplant(field, {'key': key });
        			pName = pCate.hasClass('sub') ? pCate.prev().html() : '';
                    e.preventDefault();
                    if (oUl !== null) {
                        catId = this.href.substr(this.href.indexOf('#') + 1);
                        if ($.inArray(catId, arrId) === -1) {
                            arrId.push(catId);
                            tmpLi = '<li>' + pName + ' '+this.innerHTML + '<input type="hidden" value="' + catId + '" name="' + field + '" />';
                            if(popType.match(/tvb\.com_cat/)){
                                tmpLi += '<a class="btn-up btn" href="#"><span class="ui-icon ui-icon-arrowthick-1-n"></span></a>';
                                tmpLi += '<a class="btn-dn btn" href="#"><span class="ui-icon ui-icon-arrowthick-1-s"></span></a>';
                            }
                            tmpLi += '<a class="btn-del" href="#">del</a></li>';
                            oUl.append(tmpLi);
                            if (popType.match(/tvb\.com_cat/)) {
                                updateListItem(oUl);
                            }
                        }
                    }
                });
                
                $("#pop-list .btn").bind("click", function (e) {
                    oPopList.dialog('close');
                }); 
            };
            $.get(ajaxApi, {type:popType}, populate, 'json');

        });

        $('form .editable-list li:first-child .btn-up, form .editable-list li:last-child .btn-dn').css({"visibility":"hidden"});
        $('form .editable-list .btn-up').live('click', function (e){
            e.preventDefault();
            var Ul, Li, LiPrev, LiNext, len, idx, prevVal, NextVal, tmp;
            Ul = $(this).closest('ul');
            Li = $(this).closest('li');
            len = $("li",Ul).length;
            idx = $("li",Ul).index(Li);
            if(idx==0){
                return false;
            }
            LiPrev = Li.prev("li");
            Li.insertBefore(LiPrev);
            updateListItem(Ul);
        });
        $('form .editable-list .btn-dn').live('click', function (e){
            e.preventDefault();
            var Ul, Li, LiPrev, LiNext, len, idx, prevVal, NextVal, tmp;
            Ul = $(this).closest('ul');
            Li = $(this).closest('li');
            len = $("li",Ul).length;
            idx = $("li",Ul).index(Li);
            if(idx==len-1){
                return false;
            }
            LiNext = Li.next("li");
            Li.insertAfter(LiNext);
            updateListItem(Ul);
        });

        $('form .editable-list .btn-del').live('click', function (e){
            e.preventDefault();
            var Ul = $(this).closest('ul');
            $(this).closest('li').remove();
            updateListItem(Ul);
        });

        $("form .editable-list input.editable").live("keypress", function (e) {
            var tagId;
    	    if ( !TVB.util.isControlKey(e.keyCode) ) {
                tagId = $(this).parent().find('.id');
                tagId.val('');
            }
            if (e.keyCode === 13) {    //prevent form submit while press "enter"
                e.preventDefault();
            }
        });

        //init autocomplete (current existing chapters)
        TVB.Pdes.Mod.initEditableListAutoComplete($('form[name="ane"]'));

        $("form .editable-list a.add").live('click', function (e) {
            var $input = $(this).parent().children('input.editable'),
                value = $.trim($input.val()),
                oUl = $input.prev('ul'),
                len = $('li', oUl).length,
                popType = $(this).parent().children('.type').val(),
                tagId = $(this).parent().children('.id').val(),
                tagType = 0,
                arr;

            var checkDuplicate = function (value) {
                var i = 0;
                $tag = $('li span.tag', oUl).each(function () {
                    if (this.innerHTML === value) {
                        i += 1;
                    }
                });
                return (i === 0) ? false : true;
            };
            var checkDuplicateById = function (id) {
                var i = 0;
                $('li span.tagId', oUl).each(function () {
                    if (this.innerHTML === id) {
                        i += 1;
                    }
                });
                return (i === 0) ? false : true;
            };

            e.preventDefault();

            if (len >= map[popType]['max']) {
                alert(TVB.Pdes.Config.TXT.MAX_N_ITEMS.replace(/\{n\}/g, map[popType]['max']));
                return;
            }

            //for multi-group of tags
            key = '';
            elId = $(this).closest('fieldset').find('input[name="chapter_id[]"]');
            if (elId.length > 0) {
                key = elId.val();
            }
            if (key !== '') {
                key = '[' + key + ']';
            }

            var field = map[popType].field,
                tmpLi='';
            field = TVB.util.supplant(field, {'key': key });

            if (value !== "") {
                var is_cast = popType=='cast';
                if (!checkDuplicate(value) || (is_cast && !checkDuplicateById(tagId))) {
                    if (tagId !== '') {
                        tmpLi += '<li>';
                        tmpLi += (is_cast)?'<span class="tagId">' + tagId + '</span>: ':'';
                        tmpLi += '<span class="tag">' + TVB.util.toHtmlEntities(value) + '</span>';
                        tmpLi += '<input type="hidden" value="' + tagId + '" name="' + field + '" />';
                        if(popType.match(/^tag|seo$/)){
                            tmpLi += '<a class="btn-up btn" href="#"><span class="ui-icon ui-icon-arrowthick-1-n"></span></a>';
                            tmpLi += '<a class="btn-dn btn" href="#"><span class="ui-icon ui-icon-arrowthick-1-s"></span></a>';
                        }
                        tmpLi += '<a class="btn-del" href="">del</a></li>';
                        oUl.append(tmpLi);
                        updateListItem(oUl);
                    } else {
                        if (popType === 'cast') {
                            if (confirm(TVB.Pdes.Config.TXT.CONFIRM_ADDTO_CASTDICT)) {
                                if (oPopCast === null) {
                                    oPopCast = $("#pop-cast").dialog({
                                        bgiframe: true,
                                        resizable: false,
                                        width: 600,
                                        autoOpen: false,
                                        modal: true,
                                        title: 'Add Cast'
                                    });
                                }
                                $('#pop-cast form input[type="text"]').val(value);
                                $('#pop-cast').data('bandedInput', $input);
                                oPopCast.dialog('open');
                            }
                            return;
                        } else {
                            arr = value.split(',');
                            $.each(arr, function (index, value) {
                                var value = $.trim(value);
                                var tmpLi = '';
                                if (len < map[popType]['max'] && value !== '' && !checkDuplicate(value)) {
                                    len += 1;
                                    tmpLi += '<li><span class="tag">' + TVB.util.toHtmlEntities(value) + '</span><input type="hidden" value="' + encodeURIComponent(value) + '" name="' + field + '[new]' + '" />';
                                    if(popType.match(/^tag|seo$/)){
                                        tmpLi += '<a class="btn-up btn" href="#"><span class="ui-icon ui-icon-arrowthick-1-n"></span></a>';
                                        tmpLi += '<a class="btn-dn btn" href="#"><span class="ui-icon ui-icon-arrowthick-1-s"></span></a>';
                                    }
                                    tmpLi += '<a class="btn-del" href="">del</a></li>';
                                    oUl.append(tmpLi);
                                }
                            });
                            updateListItem(oUl);
                        }
                    }
                }
                $input.val('');
            } else {
                alert(TVB.Pdes.Config.TXT.PLS_INPUT_TAG);
            }

        });

    },

    setAutoCompleteDefaults : function () {

        $.Autocompleter.defaults.minChars = 1;
        $.Autocompleter.defaults.cacheLength = 100;
        $.Autocompleter.defaults.matchSubset = false;
        $.Autocompleter.defaults.max = 10;
        $.Autocompleter.defaults.selectFirst = true;
        //$.Autocompleter.defaults.autoFill = true;
        $.Autocompleter.defaults.width = 196;
        $.Autocompleter.defaults.scroll = false;
        $.Autocompleter.defaults.scrollHeight = 200;

        //extended by simon
        $.Autocompleter.defaults.returnHandler = function (data, input) {
            var $tagId = $(input).parent().find('.id');
            $tagId.val(data.id);
        };

        //extended by simon
    	$.Autocompleter.defaults.parse = function (data) {
    		var parsed = [], type;
            var rows = eval('(' + data + ')');
    		for (var i=0; i < rows.length; i++) {
                var row = rows[i];
    			if (row) {
                    type = row.type;
    				parsed[parsed.length] = {
    					data: row,
    					value: row[type],
    					result: row[type]
    				};
    			}
    		}
    		return parsed;
    	};

        //extended by simon
	    $.Autocompleter.defaults.formatItem = function (row) {
            var type = row.type;
            return TVB.util.toHtmlEntities(row[type]);
        };
        
    },

    initEditableListAutoComplete : function (context) {
        TVB.util.once(TVB.Pdes.Mod.setAutoCompleteDefaults);
        //use closure to get the url of autocomplete ajax api
    	$('.editable-list input.editable[autocomplete="off"]', context).each(function () {
            var $this = $(this),
                popType = $(this).parent().children('.type').val(),
                options = {},
                url = $this.next('a').attr('href');
            url += url.match(/\?/) ? '&' : '?';
            if (popType === 'cast') {
                //extended by Eric
                options = {
                    parse: function (data) {
                		var parsed = [], type;
						
                        var rows = eval('('+ data + ')');
						//alert(data);
						//var header = rows[0];
						//header.name = [];
						//alert(header.name);
                		for (var i=0; i < rows.length; i++) {
							var row = rows[i];
                			if (row) {
                                type = row.type;
                				parsed[parsed.length] = {
                					data: row,
                					value: row.name[0],
                					result: row.name[0]
                				};
                			}
                		}
                		return parsed;
                	},
                    formatItem: function (row) {
						var retStr = "<span class=\"selectRow00\" title=\"ID\">"+row.id+"</span>";
						for (var i=0; i < row.name.length; i++) {
							var sContent = "";
							//get the number of Chinese char in the first 10 chars  
							var sRes = row.name[i].substring(0,10);
							var cnChar = sRes.split(/[\u4e00-\u9a05]/).length -1;
							if(row.name[i] == ""){
								sContent = "&nbsp;";
							}else if(row.name[i].length+cnChar > 9){
								sContent = row.name[i].substring(0,10-cnChar/2)+"..";
							}else{
								sContent = row.name[i];
							}
							retStr += "<span class=\"selectRow"+i+"\" title=\""+row.name[i]+"\">"+sContent+"</span>";
						}
						return retStr;
                    },
                    customInitHandler: function ($ele) {
						$ele.append("<span class=\"selectRow00 STYLE1\">ID</span>"+
                                    "<span class=\"selectRow0 STYLE1\">Master</span>"+
									"<span class=\"selectRow1 STYLE1\">Chinese</span>"+
									"<span class=\"selectRow2 STYLE1\">English 1</span>"+
									"<span class=\"selectRow3 STYLE1\">English 2</span>"+
									"<span class=\"selectRow4 STYLE1\">Other</span>"+
									"<span class=\"selectRow5 STYLE1\">Remark</span>"); 
                    },
                    width: 600,
                    resultsClass: "ac_results cast"
                };
            }
            if ($this.data('autocomplete') !== true) {    //prevent init twice
                $this.autocomplete(url + 'type=name', options);
            }
        });
    },

    initPopFind : function () {
        var oPopFind = null;
        var oFind = null;
        var oPopList = null;
        var currentFindType = '';
        var unpublish;
        var premium;

        var disable_formitem = function (field, disable, form){
            var formitem,
                form = form || '';
                input = $(form + ' *[value="' + field + '"]', oFind);
                
            if(input.length > 0){
                formitem = input.closest(".form-item"); 
                if(disable){
                    $("input, select",formitem).attr("disabled","disabled");
                    formitem.hide();
                }else{
                    $("input, select",formitem).removeAttr("disabled");
                    formitem.show();
                }
            }
        };
            
        var resetForm = function (e){
            $(".advance-form .removeFilter:gt(0)", oFind).click();
            $("#find_programme_id").val('');
            $('#find2_folder').attr('disabled', 'disabled');
            disable_formitem('premium_items', true);
        };
        
        var addFilter = function (e){
            var lastFilter = $(".filter-line:last", oFind);
            var newFilter = lastFilter.clone(true);
            $(".searchField", newFilter).val('');
            $(".searchOper", newFilter).val('');
            $(".searchString", newFilter).val('');
            newFilter.insertAfter(lastFilter);
            $(".removeFilter", newFilter).show();
            
        };
        var removeFilter = function (e){ 
            $(this).closest(".filter-line").remove();    
        };
        
        var checkSubmit = function (e){
            var oForm = this;
            var mode = ($(this).hasClass("advance-form"))?'advance':'simple';
            var type; 
            var searchFields = [], searchOpers = [], searchStrings = [],sf,so,ss,l,i;
            if( $("input[name='type']",oForm).length == 1 ){
                type = oForm.type.value;
            }
            
            if( type == 'address' || type == 'recipe' || type == 'song' || type == 'biography' || 
                type == 'award' || type == 'product' || type == 'qa' || type == 'general_info' || type == 'pageant' ) {
                var programme_id = $('#find_programme_id',this).val();

                if( !programme_id ){
                    alert(TVB.Pdes.Config.TXT.PROGRAMME_NOT_FOUND);
                    return false;
                }
            }else if(type == 'programme' || type == 'episode' || type == 'cast' || type == 'image' || type == 'video'){
                if(mode == 'advance'){
                    searchFields = $(".advance-form .searchField", oFind);
                    searchOpers = $(".advance-form .searchOper", oFind);
                    searchStrings = $(".advance-form .searchString", oFind);
                    l = searchFields.length;
                    for(i=0; i<l; i++){
                        sf = searchFields[i].value;
                        so = searchOpers[i].value;
                        if(sf != 'tvbcom_category'){ //
                            for(var j=i+1; j<l; j++){
                                if(!!sf && searchFields[j].value == sf && searchOpers[j].value == so ){
                                    if(searchOpers[j].value != 'ne' && searchOpers[j].value != 'cn'){
                                        alert(TVB.Pdes.Config.TXT.SEARCH_FIELDS_CONFLICT);
                                        return false;
                                    }
                                }
                            }
                        }
                    }                    
                    
                }else{ //simple mode
                    $(".simple-form input[name^='searchField']", oFind).each(function () {
                        var parent = this.parentNode;
                        var $searchString = $('*[name^="searchString"]', parent);
                        sf = this.value;
                        ss = $.trim($searchString.val());
                        if (ss == '') {
                            disable_formitem(sf, 1);
                        } else if ($searchString.get(0).type === 'text') {
                            searchFields.push(this);
                            searchOpers.push($('input[name^="searchOper"]').get(0));
                            searchStrings.push($searchString.get(0));
                            l = searchFields.length;
                        }
                    });
                    if($('#find2_programme_id', oForm).val()){
                        disable_formitem('path', 1);
                        disable_formitem('title', 1);
                    }
                }
                
                // convert category text to id;
                for(i=0; i<l; i++){
                    if(searchFields[i].value == 'tvbcom_category'){
                        searchOpers[i].value = 'eq';    //for advance mode
                        searchStrings[i].value = $(searchStrings[i]).data('cat_id');
                    }
                }

            }else{
            
            }
        };
        
        var pop_tvbcom_cat = function (oTarget){
            var ajaxApi = TVB.Pdes.Config.URL.GET_TVBCOM_CAT;
            if (oPopList === null) {
                oPopList = $("#pop-list").dialog({
                    bgiframe: true,
                    resizable: false,
                    width: 600,
                    autoOpen: false,
                    modal: true,
                    close: function (event, ui){
                        oPopFind.dialog('close');
                        oPopFind.dialog('open');
                    }
                });
            }
            
            $("#pop-list div.bd").html('');
            oPopList.dialog('option', 'title', TVB.Pdes.Config.TXT.SEL_TVBCOM_CAT);
            oPopList.dialog('open');

            var populate = function (data) {
                var html = [];
                html[html.length] = '<ul>';
                for (var i = 0, l = data.length; i < l; i += 1) {
                    html[html.length] = '<li>';
                    
                    html[html.length] = '<a href="#' + data[i].id + '">' + data[i].name + '</a>';
                                   
                    if (typeof data[i].child !== 'undefined' && data[i].child.length > 0) {
                        html[html.length] = '<ul class="sub">';
                        for (var j = 0; j < data[i].child.length; j += 1) {
                            html[html.length] = '<li>';
                            
                            html[html.length] = '<a href="#' + data[i].child[j].id + '">' + data[i].child[j].name + '</a>';
                            
                            html[html.length] = '</li>';   
                        }
                        html[html.length] = '</ul>';
                    }
                    html[html.length] = '</li>';                   
                }
                html[html.length] = '</ul>';
                $("#pop-list div.bd").html(html.join(''));
                
                $("#pop-list .bd a").unbind("click").bind("click", function (e) {
                    e.preventDefault();
                    
                    var pCate = $(this).parent().parent();
        			var pName = "";
                    var cName = this.innerHTML;
                    var cId = this.href.replace(/.*#/,'');
                    
        			pName = pCate.hasClass('sub') ? pCate.prev().html() : '';
        			cName = (pName === '')?cName:(pName +' '+ cName);
        			
        			$(oTarget).data('cat_id', cId);
                    
                    oTarget.value = cName;
                    oPopList.dialog('close');
                });
                
                $("#pop-list .btn").unbind("click").bind("click", function (e) {
                    oPopList.dialog('close');
                }); 
            };
            $.get(ajaxApi, {}, populate, 'json');
        };
        //searchString Focus
        var ss_focus = function (e){
            var idx = $(".searchString", oFind).index(this);
            if('tvbcom_category' == $(".searchField", oFind)[idx].value){
                pop_tvbcom_cat(this);
            }
        };
        var sf_change = function (e){
            var idx = $(".searchField", oFind).index(this);
            
            if('tvbcom_category' == this.value){
                $(".searchOper", oFind)[idx].value = 'eq';
                $(".searchString", oFind)[idx].value = '';
                pop_tvbcom_cat($(".searchString", oFind)[idx]);
            }
        };
        var so_change = function (e){
            var idx = $(".searchOper", oFind).index(this);
            
            if('tvbcom_category' == $(".searchField", oFind)[idx].value){
                this.value = 'eq';
            }
        };
        
        var switch_mode = function (e){            
            if($(this).hasClass('simple-btn')){
                $(".advance-form", oFind).hide();
                $(".simple-form", oFind).show();                
            }else{
                $(".simple-form", oFind).hide();
                $(".advance-form", oFind).show();
            }
        };
        
        var find_all = function (e){
            var oForm = this.form;
            
            var type = oForm.type.value;
            var unpublish = oForm.unpublish.value;
            var premium = oForm.premium.value;
            var url = oForm.action;
            url += url.match(/\?/) ? '&' : '?';
            url += 'type='+type+'&unpublish='+unpublish+'&premium='+premium;
            location.href = url;            
        };
        
        //add event handler to mainnav
        $('#cms_header a.btn-find').bind("click", function (e) {
            e.preventDefault();
            
            //show pop-find by class
            $("#pop-find>div").hide();
            
            var cla = $(this).attr('href').replace(/\.*#/,'');
            unpublish = $(this).hasClass("unpublish")? 1 : 0;
            premium = $(this).hasClass("premium")? 1 : 0;
            currentFindType = cla;
            oFind = $("#pop-find ."+cla);
            oFind.show();
            $(".advance-form", oFind).hide();
            $(".simple-form", oFind).show(); 
            
            $("input[type='reset']", oFind).click();
            $("input[name='type']", oFind).val(cla);
            $("input[name='unpublish']", oFind).val(unpublish); 
            $("input[name='premium']", oFind).val(premium); 

            $("option[value='record_status'],option[value='modified_by'],option[value='modified_at']", oFind).css({'display':(unpublish?'none':'')});

            disable_formitem('record_status', unpublish, '.simple-form');
            disable_formitem('modified_by', unpublish, '.simple-form');
            disable_formitem('modified_at', unpublish, '.simple-form');

            disable_formitem('premium', premium);
            disable_formitem('premium_items', !premium);    //find => true, unpublish => true, premium => false

            if (oPopFind === null) {
                oPopFind = $("#pop-find").dialog({
                    bgiframe: true,
                    resizable: false,
                    width: 650,
                    autoOpen: false,
                    modal: true
                });
            }
            oPopFind.dialog('option', 'title', 'Find ' + this.innerHTML);
            oPopFind.dialog('open');
            $(this).closest('li.ui-state-hover').removeClass('ui-state-hover');
        }); 
        
        // show/hide "premium_items" according to the vaule of "premium".
        $("form input.premium", oFind).change(function () {
            var formClass;
            if (!unpublish) {    // only affect normal find
                formClass = $(this).closest('form').attr('class');    //only show/hide current form's items
                disable_formitem('premium_items', this.value !== '1', '.' + formClass);
            }
        });

        $(".simple-form .advance-btn,.advance-form .simple-btn").bind("click", switch_mode);        
        
        $(".advance-form .addFilter", oFind).unbind("click").bind("click", addFilter);
        $(".advance-form .removeFilter", oFind).unbind("click").bind("click", removeFilter);
        $(".advance-form .removeFilter:first", oFind).hide();
        
        $(".advance-form .searchField", oFind).bind("change", sf_change);
        $(".advance-form .searchOper", oFind).bind("change", so_change);
        $(".advance-form .searchString", oFind).bind("focus", ss_focus);    
        $("#find2_tvbcom_category", oFind).bind("focus", function (){ pop_tvbcom_cat(this); });
        
        $("#pop-find input[type='reset']").bind("click", resetForm);
        $("#pop-find .buttons input[value='All']").bind("click", find_all);
        $("#pop-find form").bind("submit", checkSubmit); 
        
        var AC_programme_find = function (){    //autoComplete programme... find info
        
            var url = TVB.Pdes.Config.URL.GET_PROGRAMME;
            url += url.match(/\?/) ? '&' : '?';        
            
            var arrId = ['find_programme_id', 'find_programme_path', 'find_programme_title_cn', 'find_programme_title_en', 'find_programme_eps', 'find_onair_episode_no'];
    
            var reset = function (input) {
                var len = arrId.length,
                    oForm = input.form,
                    exceptionId = input.id;
                for (var i = 0; i < len; i += 1) {
                    if (exceptionId !== arrId[i]) {
                        $('#' + arrId[i], oForm).val('');
                    }
                }
            };
            
            var autocomp_obj = {
                width : 282,
                returnHandler : function (data, input) {
                    var len = arrId.length,
                        key,
                        id = input.id,
                        oForm = input.form;
                    for (var i = 0; i < len; i += 1) {
                        if (id !== arrId[i]) {
                            key = arrId[i].substr(15);
                            $('#' + arrId[i], oForm).val(data[key]);
                        }
                    }
                },
                extraParams : {
                    unpublish : function (){return $("input[name='unpublish']", oFind).val();},
                    premium : function (){return $("input[name='premium']", oFind).val();}
                }
            };        
            
            $(".info #find_programme_id").autocomplete(url + 'type=id', autocomp_obj);
            $(".info #find_programme_title_en").autocomplete(url + 'type=title_en', autocomp_obj);
        	$(".info #find_programme_title_cn").autocomplete(url + 'type=title_cn', autocomp_obj);
        	$(".info #find_programme_path").autocomplete(url + 'type=path', autocomp_obj);
        	
        	$(".info #find_programme_id, .info #find_programme_title_en, .info #find_programme_title_cn, .info #find_programme_path").keyup( function (event) {
        	    if ( !TVB.util.isControlKey(event.keyCode) ) {
                    reset(this);
                }
            });
        };

        var updateFolderList = function (input) {
            var pid, url;
            if (currentFindType === 'video' || currentFindType === 'image') {
                pid = $(input).closest('fieldset').find('#find2_programme_id').val();
                if (pid !== '') {
                    url = TVB.Pdes.Config.URL.GET_FOLDERS;
                    url += url.match(/\?/) ? '&' : '?'; 
                    $.getJSON(url, {
                        'id': pid,
                        'type': 'programme',
                        'folder_item_type': currentFindType,
                        't': (new Date()).valueOf()
                    }, function (data) {
                        var $folder = $(input).closest('fieldset').find('#find2_folder');
                        var arrOptions = ['<option value="">all</option>'];
                        $folder.attr('disabled', '');
                        for (var i = 0; i < data.length; i += 1) {
                            if (data[i].has_item === '1') {    //do not show empty folder 
                                arrOptions[arrOptions.length] = '<option value="' + data[i].id + '">' + data[i].title_en + ' ' + data[i].title_cn + '</option>';
                            }
                        }
                        $folder.html(arrOptions.join(''));
                    });
                }
            }
        };

        var AC_programme_find2 = function (){ //autoComplete programme... simple find(programme,episode,cast,image,video) 
            var url = TVB.Pdes.Config.URL.GET_PROGRAMME2;
            url += url.match(/\?/) ? '&' : '?';        

            var arrId = ['find2_programme_id', 'find2_programme_path', 'find2_programme_title'];
    
            var reset = function (input) {
                var len = arrId.length,
                    oForm = input.form,
                    exceptionId = input.id;
                for (var i = 0; i < len; i += 1) {
                    if (exceptionId !== arrId[i]) {
                        $('#' + arrId[i], oForm).val('');
                    }
                }
                $(input).closest('fieldset').find('#find2_folder').html('').attr('disabled', 'disabled');
            };

            var autocomp_obj = {
                width : 252,
                returnHandler : function (data, input) {
                    var len = arrId.length,
                        key,
                        id = input.id,
                        oForm = input.form;
                    for (var i = 0; i < len; i += 1) {
                        if (id !== arrId[i]) {
                            key = arrId[i].substr(16);
                            $('#' + arrId[i], oForm).val(data[key]);
                        }
                    }
                    setTimeout(function () {
                        updateFolderList(input);
                    }, 100);
                },
                extraParams : {
                    unpublish : function (){return $("input[name='unpublish']", oFind).val();},
                    premium : function (){return $("input[name='premium']", oFind).val();}
                }
            };        
            
            $(".simple-form #find2_programme_id").autocomplete(url + 'type=id', autocomp_obj);
            $(".simple-form #find2_programme_title").autocomplete(url + 'type=title', autocomp_obj);
        	$(".simple-form #find2_programme_path").autocomplete(url + 'type=path', autocomp_obj);
        	$(".simple-form #find2_programme_id, .simple-form #find2_programme_title, .simple-form #find2_programme_path").keyup( function (event) {
        	    if ( !TVB.util.isControlKey(event.keyCode) ) {
                    reset(this);
                }
            });
        };
        TVB.util.once(TVB.Pdes.Mod.setAutoCompleteDefaults);        
        AC_programme_find();
        AC_programme_find2();
    },

    initLoadProgrammeSubCat : function () {
        var get_tvbcom_auto_subcat_url = TVB.Pdes.Config.URL.GET_TVBCOM_AUTO_SUBCAT;
        get_tvbcom_auto_subcat_url += (get_tvbcom_auto_subcat_url.match(/\?/)) ? '&' : '?';
        var get_programme_subcat_url = TVB.Pdes.Config.URL.GET_PROGRAMME_SUBCAT;
        get_programme_subcat_url += (get_programme_subcat_url.match(/\?/)) ? '&' : '?';
        
        var loadSubCat = function (e){
            var _this = $(this);
            var _sub = $("#programe-category-selector select[name='cpl_category_id']");
            var _parent = $("#programe-category-selector select[name='parent_cpl_category']"); 
            var cat_id = _this.val();            
            
            var get_autoCategory = function () {
				cat_id = _parent.val()==cat_id ? 0 : cat_id;
				$.get(get_tvbcom_auto_subcat_url + '&pid='+_parent.val()+'&sid='+cat_id, function (data) {
					
                    var o = eval("("+data+")");
					var l = o.length;
					var oUl = $('#programe-category-selector').next().find('.ui-widget-content');
					var len = oUl.children().length;
					var tmpLi;
					
					var check = function (val) {
						var b = false;			
						for(var i=0;i<len;i++) {	
							if($(oUl.children().get(i)).find('input[type="hidden"]').val()==val) {
								return true;
							}
						
						}
						return b;
					};
					
					//;
					for(var i=0;i<l;i++) {	
						if(!check(o[i].id)) {
						    tmpLi = '<li>'+ o[i].title +'<input type="hidden" name="tvbcom_cat_id[]" value="'+ o[i].id +'"/>';
						    tmpLi += '<a class="btn-up btn" href="#"><span class="ui-icon ui-icon-arrowthick-1-n"></span></a>';
                            tmpLi += '<a class="btn-dn btn" href="#"><span class="ui-icon ui-icon-arrowthick-1-s"></span></a>';
                            tmpLi += '<a class="btn-del" href="#">del</a></li>';
                            
                            oUl.append(tmpLi);
                            $("input[name^='tvbcom_cat_id']",oUl).each(function(i){
                                $(this).attr("name","tvbcom_cat_id["+i+"]");
                            });
                            $('.btn-up,.btn-dn',oUl).css({"visibility":"visible"});
                            $('li:first .btn-up,li:last .btn-dn',oUl).css({"visibility":"hidden"});
                    	}
					}

                });	
			};
            
            //$("input[name='id']", _this.closest("form")).val('');
            if(_this[0].name == _sub[0].name){
                get_autoCategory();
                return false;
            }            
            
            var emptyOpt = "<option value='0'>Please Select...</option>";
            if('0' == cat_id){        
                _sub.html(emptyOpt);
            }else{
                $.get(get_programme_subcat_url + '&id='+cat_id, function (data) {
                    var oJson = eval('('+data+')');
            
                    var opts = emptyOpt;
                    for(var i in oJson){
                        if (oJson.hasOwnProperty(i)) {
                            opts += "<option value='" + i + "'>"+ oJson[i] +"</option>";
                        }
                    }
                    $(_sub).html(opts);
					if($(_sub).children().length===1) {
						//no child
						get_autoCategory();
					}
                });
            }
        };
        
        $("#programe-category-selector select[name='parent_cpl_category'], #programe-category-selector select[name='cpl_category_id']").bind("change", loadSubCat);
    },
    
    initLoadCuisineSubCat : function () {
        var url = TVB.Pdes.Config.URL.GET_CUISINE_SUBCAT;
        url += (url.match(/\?/)) ? '&' : '?';
        var loadSubCat = function (e){
            var _this = $(this);
            var _sub = $("#cuisine-category-selector select[name='cuisine_sub_category']");
            
            var cat_id = _this.val();
            
            //$("input[name='id']", _this.closest("form")).val('');
            if(_this[0].name == _sub[0].name){
                //$("input[name='id']", _this.closest("form")).val(cat_id);
                return false;
            }
            
            var emptyOpt = "";
            if('0' == cat_id){        
                _sub.html(emptyOpt);
            }else{
                $.get(url + '&id='+cat_id, function (data) {
                    var oJson = eval('('+data+')');
            
                    var opts = emptyOpt;
                    for(var i in oJson){
                        if (oJson.hasOwnProperty(i)) {
                            opts += "<option value='" + i + "'>"+ oJson[i] +"</option>";
                        }
                    }
                    $(_sub).html(opts);
                });
            }
        };
        
        $("#cuisine-category-selector select[name='cuisine_category'], #cuisine-category-selector select[name='cuisine_sub_category']").bind("change", loadSubCat);
    },
    
    initLocationAutoComplete : function () {
        TVB.util.once(TVB.Pdes.Mod.setAutoCompleteDefaults);
    
        var url = TVB.Pdes.Config.URL.GET_LOCATION;
        url += (url.match(/\?/)) ? '&' : '?';
        
        //extended by honk
        var returnHandler = function (data, input) {
            var id = data.id;
            var input_id = input.id;  
            if( input_id == 'country_autocomplete' ){    
                $("#province_state_autocomplete").flushCache().setOptions({url: url + 'country_id=' + id});
                $("#country").val(id);
            }else if( input_id == 'province_state_autocomplete' ){
                $("#province_state").val(id);
            }
            input.blur();
        };

        //extended by honk
    	var parse = function (data) { 
    		var parsed = [], name;
            var rows = eval('(' + data + ')');
    		for (var i=0; i < rows.length; i++) {
                var row = rows[i]; 
    			if (row) {
    				parsed[parsed.length] = {
    					data: row,
    					value: row.id,
    					result: row.name
    				};
    			}
    		}
    		return parsed;
    	};

        //extended by honk
	    var formatItem = function (row) {             
            return TVB.util.toHtmlEntities(row.name);
        };

        var _param = {parse:parse, formatItem:formatItem, returnHandler:returnHandler};

    	$("#country_autocomplete").autocomplete(url, _param).keyup( function (event) {
            if( !TVB.util.isControlKey(event.keyCode) ){
                $("#province_state_autocomplete").flushCache().setOptions({url: url + 'country_id='});
                $("#country").val('');
                $("#province_state").val('');
                $("#province_state_autocomplete").val('');
            }
        });

        $("#province_state_autocomplete").autocomplete(url + 'country_id=', _param).keyup( function (e) {
            if( !TVB.util.isControlKey(e.keyCode) ){
                $("#province_state").val('');
            }
        });
        
        var country_id = $("#country").val();
        if( country_id ){
            $("#province_state_autocomplete").autocomplete(url + 'country_id='+country_id, _param);
        }
    },

    initBackButton: function () {
        $('#pms-ane form[name="ane"] .buttons input').bind("click", function (e) {
            var value = $(this).val(),
                url;
            if ($(this).hasClass('back')) {
                url = TVB.Pdes.Mod.getUrlInSession();
                if (url !== "") {
					location.href = url;
				} else {					
					history.go(-1);
				}
            } else if ($(this).hasClass('top')) {
                window.scrollTo(0, 0);
            } else if (!$(this).hasClass('add-chapter') && !$(this).hasClass('edit') && !$(this).hasClass('clone') && !$(this).hasClass('blue')) {
                if ($(this).hasClass('delete') && TVB.util.isSet('TVB.Pdes.Vars.isCloned') && TVB.Pdes.Vars.isCloned === true) {
                    if (!confirm(TVB.Pdes.Config.TXT.CONFIRM_DEL_CLONED_RECORD)) {
                        e.preventDefault(e);            
                    }
                } else {
                    if (!confirm(TVB.Pdes.Config.TXT.CONFIRM_DO_RECORD.replace(/\{do\}/g,value))) {
                        e.preventDefault(e); 
                        if($("input[name='is_folder_update']").length > 0){
                            $("input[name='is_folder_update']").val('0');
                        }
                    } else if (this.type === 'reset') {
                        this.form.action += (this.form.action.match(/\?/) ? '&' : '?') + 'reset=1';
                        this.form.submit();
                    }
                }
            }
        });
    },

    initValidation: function () {
        if ($.validator) {
            /* extend error code to jQuery validation plugin */
            $.validator.messages = {
        		required: "PDES0001e :- This field is required.",
        		remote: "PDES0002e :- Please fix this field.",
        		email: "PDES0003e :- Please enter a valid email address.",
        		url: "PDES0004e :- Please enter a valid URL.",
        		date: "PDES0005e :- Please enter a valid date.",
        		dateISO: "PDES0006e :- Please enter a valid date (ISO).",
        		dateDE: "PDES0007e :- Bitte geben Sie ein gültiges Datum ein.",
        		number: "PDES0008e :- Please enter a valid number.",
        		numberDE: "PDES0009e :- Bitte geben Sie eine Nummer ein.",
        		digits: "PDES0010e :- Please enter only digits",
        		creditcard: "PDES0011e :- Please enter a valid credit card number.",
        		equalTo: "PDES0012e :- Please enter the same value again.",
        		accept: "PDES0013e :- Please enter a value with a valid extension.",
        		maxlength: $.format("PDES0014e :- Please enter no more than {0} characters."),
        		minlength: $.format("PDES0015e :- Please enter at least {0} characters."),
        		rangelength: $.format("PDES0016e :- Please enter a value between {0} and {1} characters long."),
        		range: $.format("PDES0017e :- Please enter a value between {0} and {1}."),
        		max: $.format("PDES0018e :- Please enter a value less than or equal to {0}."),
        		min: $.format("PDES0019e :- Please enter a value greater than or equal to {0}.")
        	};
            $.validator.addMethod('regexp', function (value, element, params) {
                var regex = new RegExp(params.substring(1, params.length-1));
                var result = this.optional(element) || regex.test(value);
                return result;	
            }, "PDES0020e :- Invalid format");
            $.validator.addMethod('path', function (value, element) {
                return this.optional(element) || /^[a-zA-Z]\w*$/.test(value);
            }, "PDES0021e :- Alphanumeric. Shoulde begin with character.");
            $.validator.addMethod('english', function (value, element) {
                return this.optional(element) || /^[\x00-\xff]*$/.test(value);
            }, "PDES0022e :- Alphanumeric and punctuation only.");
            $.validator.addMethod('positiveInt', function (value, element) {
                return this.optional(element) || /^[1-9]\d*$/.test(value);
            }, "PDES0023e :- Positive integer only.");

            $.validator.addMethod('epsUnique', function (value, element) {
                var strEps = $('#programme_eps').val();
                var pattern;
                if (typeof strEps !== 'undefined') {
                    pattern = new RegExp('(^|,)' + value + '(,|$)');
                    return this.optional(element) || !pattern.test(strEps);
                } else {
                    return this.optional(element);
                }
            }, "PDES0030e :- Episode No. has already exist.");

            $.validator.addMethod('epsExist', function (value, element) {
                var strEps = $('#programme_eps').val();
                var pattern;
                if (typeof strEps !== 'undefined') {
                    pattern = new RegExp('(^|,)' + value + '(,|$)');
                    return this.optional(element) || pattern.test(strEps);
                } else {
                    return this.optional(element);
                }
            }, "PDES0031e :- Episode No. does not exist.");

            $.validator.addMethod('inAcList', function (value, element) {
                var joHidden = $(element).parent().children(':hidden');
                if (value !== '' && joHidden.val() === '') {
                    return false;
                }
                return true;
            }, "PDES0032e :- You must enter a value matched in the list.");

            //ignor hidden fileds
            $.validator.defaults.ignore = ':hidden';

            if (TVB.util.isSet('TVB.Pdes.oValidation')) {
                $(TVB.Pdes.oValidation.form).validate({
                    rules: TVB.Pdes.oValidation.rules,
                    errorClass: "error"
                });
            }

        }
    },
    
    initTopClock : function () {
        
        var clock = document.getElementById("top-clock"); 
        
        var didadida = function (){            
            
            var arr = clock.innerHTML.match(/\d+/g);
            var Y = Number(arr[0]);
            var m = Number(arr[1])-1;
            var d = Number(arr[2]);
            var H = Number(arr[3]);
            var i = Number(arr[4])+1;
            var date = new Date(Y,m,d,H,i);
            
            Y = date.getFullYear();
            m = date.getMonth()+1;
            d = date.getDate();
            H = date.getHours();
            i = date.getMinutes();
            
            m = (m<10) ? ('0'+m) : m;
            d = (d<10) ? ('0'+d) : d;
            H = (H<10) ? ('0'+H) : H;
            i = (i<10) ? ('0'+i) : i;
            
            clock.innerHTML = Y+'-'+m+'-'+d+' '+H+':'+i;
        };
        
        setInterval(didadida, 60000);
    },
    
    extendJqgrid : function () {
        
        $(".ui-pg-input").keyup( function () {
            this.value = this.value.replace(/[^\d]/g,'');
            var max = Number($(this).next("span").html());
            var val = Number(this.value);
            if(this.value>max){
                this.value=max;
            }
        });
        
        $("#result-pager1_left").width(300);
        $("#result-pager1_center").width(330);
    },
    
    initResultList : function () {
        var type = TVB.Pdes.oParam.type;         
        if(!type){return false;}
        
        var unpublish = (TVB.Pdes.oParam.unpublish == '1') ? true : false, 
            premium = (TVB.Pdes.oParam.premium == '1') ? true : false, 
            str_record_status = unpublish ? 'Status' : 'Record Status',
            str_modified_by = unpublish ? 'Performed By' : 'Modified By',
            str_modified_at = unpublish ? 'Performed At' : 'Modified At',
            jg = $("#result-list1"),
            listUrls = {
                'programme'     : TVB.Pdes.Config.URL.GET_PROGRAMME_LIST,
                'episode'       : TVB.Pdes.Config.URL.GET_EPISODE_LIST,
                'cast'          : TVB.Pdes.Config.URL.GET_CAST_LIST,
                'image'         : TVB.Pdes.Config.URL.GET_IMAGE_LIST,
                'video'         : TVB.Pdes.Config.URL.GET_VIDEO_LIST,
				'premium_video' : TVB.Pdes.Config.URL.GET_VIDEO_LIST,
                'info'          : TVB.Pdes.Config.URL.GET_INFO_LIST
            };
        
            cols = {
                'programme' : {
                    'colNames' : ['ID', 'Path', 'Title', 'Company Code <br />&amp; Programme No.', 'TVB.COM Category', str_record_status, str_modified_by, str_modified_at, 'Action Buttons'],
                   	'colModel' : [
                   		{'name':'id', 'index':'id', 'width':'65'},
                   		{'name':'path', 'index':'path', 'width':'150'},
                   		{'name':'title', 'index':'title', 'width':'150'},
                   		{'name':'company_code_cpl', 'index':'company_code_cpl', 'width':'150'},		
                   		{'name':'tvbcom_category', 'index':'tvbcom_category', 'width':'150'},
                   		{'name':'record_status', 'index':'record_status', 'width':'110', 'sortable':(!unpublish)},
                   		{'name':'modified_by', 'index':'modified_by', 'width':'100', 'sortable':(!unpublish)},
                   		{'name':'modified_at', 'index':'modified_at', 'width':'100', 'sortable':(!unpublish)},
                   		{'name':'op', 'index':'op', 'sortable':false, 'width':'150'}
                   	],
                   	'tabs' : [
                   	    {'cols':['modified_by']},
                   	    {'cols':['modified_at']},
                        {'cols':['op'],'checked':true}
                    ]
                },
                'episode' : {
                    'colNames' : ['ID', 'Programme Title', 'On Air Episode No.', 'On Air Date/Time', str_record_status, str_modified_by, str_modified_at,'Action Buttons'],
                   	'colModel' : [
                   		{'name':'id', 'index':'id', 'width':'65'},
                   		{'name':'title', 'index':'title', 'width':'150'},
                   		{'name':'onair_episode_no', 'index':'onair_episode_no', 'width':'150'},
                   		{'name':'premier_time_onAir', 'index':'premier_time_onair', 'width':'150'},
                   		{'name':'record_status', 'index':'record_status', 'width':'110', 'sortable':(!unpublish)},
                        {'name':'modified_by', 'index':'modified_by', 'width':'100', 'sortable':(!unpublish)},	
                   		{'name':'modified_at', 'index':'modified_at', 'width':'100', 'sortable':(!unpublish)},
                   		{'name':'op', 'index':'op', 'sortable':false, 'width':'150'}
                   	],
                   	'tabs' : [
                   	    {'cols':['modified_by']},
                   	    {'cols':['modified_at']}
                    ]
                },
                'cast' : {
                    'colNames' : ['ID', 'Programme Title', 'Name', 'Cast Name', 'Other Name', 'Cast Nickname', str_record_status, str_modified_by, str_modified_at,'Action Buttons'],
                   	'colModel' : [
                   		{'name':'id', 'index':'id', 'width':'65'},
                   		{'name':'title', 'index':'title', 'width':'120'},
                   		{'name':'real_name', 'index':'real_name', 'width':'100'},
                   		{'name':'cast_name', 'index':'cast_name', 'width':'100'},
                   		{'name':'other_name', 'index':'other_name', 'width':'100'},
                   		{'name':'nickname', 'index':'nickname', 'width':'100'},
                   		{'name':'record_status', 'index':'record_status', 'width':'110', 'sortable':(!unpublish)},
                        {'name':'modified_by', 'index':'modified_by', 'width':'100', 'sortable':(!unpublish)},	
                   		{'name':'modified_at', 'index':'modified_at', 'width':'100', 'sortable':(!unpublish)},
                   		{'name':'op', 'index':'op', 'sortable':false, 'width':'150'}
                   	],
                   	'tabs' : [
                   	    {'cols':['modified_by']},
                   	    {'cols':['modified_at']}
                    ]
                },
                'image' : {
                    'colNames' : ['ID', 'Programme Title', 'Image Title', str_record_status, str_modified_by, str_modified_at, 'Action Buttons'],
                   	'colModel' : [
            			{'name':'id', 'index':'id', 'width':'65'},
                   		{'name':'title', 'index':'title', 'width':'200'},
                   		{'name':'image_title', 'index':'image_title', 'width':'200'},
                   		{'name':'record_status', 'index':'record_status', 'width':'110', 'sortable':(!unpublish)},
                   		{'name':'modified_by', 'index':'modified_by', 'width':'100', 'sortable':(!unpublish)},
                   		{'name':'modified_at', 'index':'modified_at', 'width':'100', 'sortable':(!unpublish)},	
                   		{'name':'op', 'index':'op', 'sortable':false, 'width':'150'}
                   	]
                },
                'video' : {
                    'colNames' : ['ID', 'Programme Title', 'On Air Episode No.', 'Video Title', str_record_status, str_modified_by, str_modified_at, 'Action Buttons'],
                   	'colModel' : [
            			{'name':'id', 'index':'id', 'width':'65'},
                   		{'name':'title', 'index':'title', 'width':'140'},
                   		{'name':'onair_episode_no', 'index':'onair_episode_no', 'width':'140'},
                   		{'name':'video_title', 'index':'video_title', 'width':'140'},
                   		{'name':'record_status', 'index':'record_status', 'width':'110', 'sortable':(!unpublish)},
                   		{'name':'modified_by', 'index':'modified_by', 'width':'100', 'sortable':(!unpublish)},
                   		{'name':'modified_at', 'index':'modified_at', 'width':'100', 'sortable':(!unpublish)},	
                   		{'name':'op', 'index':'op', 'sortable':false, 'width':'180'}
                   	],
                   	'tabs' : [
                   	    {'cols':['modified_by']},
                   	    {'cols':['modified_at']}
                    ]
                },
				 'premium_video' : {
                    'colNames' : ['ID', 'Programme Title', 'On Air Episode No.', 'Video Title', str_record_status, 'Expired', str_modified_by, str_modified_at, 'Action Buttons'],
                   	'colModel' : [
            			{'name':'id', 'index':'id', 'width':'65'},
                   		{'name':'title', 'index':'title', 'width':'140'},
                   		{'name':'onair_episode_no', 'index':'onair_episode_no', 'width':'100'},
                   		{'name':'video_title', 'index':'video_title', 'width':'140'},
                   		{'name':'record_status', 'index':'record_status', 'width':'110', 'sortable':(!unpublish)},
						{'name':'expiry_status', 'index':'expiry_status', 'width':'60'},
                   		{'name':'modified_by', 'index':'modified_by', 'width':'100', 'sortable':(!unpublish)},
                   		{'name':'modified_at', 'index':'modified_at', 'width':'100', 'sortable':(!unpublish)},	
                   		{'name':'op', 'index':'op', 'sortable':false, 'width':'100'}
                   	],
                   	'tabs' : [
                   	    {'cols':['modified_by']},
                   	    {'cols':['modified_at']}
                    ]
                },
                'info' : {
                    'colNames' : ['ID', 'Programme Title', 'On Air Episode No.', 'Info Title', str_record_status, str_modified_by, str_modified_at, 'Action Buttons'],
                   	'colModel' : [
                   		{'name':'id', 'index':'id', 'width':'65'},
                   		{'name':'title', 'index':'title', 'width':'150'},       		
                   		{'name':'onair_episode_no', 'index':'onair_episode_no', 'width':'150'},
                   		{'name':'infoTitle', 'index':'infoTitle', 'width':'150'},
                   		{'name':'record_status', 'index':'record_status', 'width':'110', 'sortable':(!unpublish)},
                   		{'name':'modified_by', 'index':'modified_by', 'width':'100', 'sortable':(!unpublish)},
                   		{'name':'modified_at', 'index':'modified_at', 'width':'100', 'sortable':(!unpublish)},
                   		{'name':'op', 'index':'op', 'sortable':false, 'width':'150'}
                   	],
                   	'tabs' : [
                   	    {'cols':['modified_by']},
                   	    {'cols':['modified_at']}
                    ]
                }
            };
    
        if( type == 'address' || type == 'recipe' || type == 'song' || 
            type == 'biography' || type == 'award' || type == 'product' || 
            type == 'qa' || type == 'general_info' || type == 'pageant' ){
                type = 'info';
        }
		
		if(premium && type=='video'){
			 type = 'premium_video';
		}
        
        var listUrl = listUrls[type];
        listUrl += listUrl.match(/\?/) ? '&' : '?';
        var colNames = cols[type].colNames,
            colModel = cols[type].colModel,
            multiselect = false,
            jg_options = {
               	url: listUrl + ((window.location.search)?window.location.search.substr(1):''),
            	datatype : "json",
               	colNames : colNames,
               	colModel : colModel,
               	rowNum : 10,
               	rowList : [10,20,30,40,50],
               	imgpath : '',
               	pager : jQuery('#result-pager1'),
               	sortname : 'modified_at',
                viewrecords : true,
                sortorder : "desc",
                height: "auto",
                caption : "",
                multiselect : multiselect
            },            
            tabs = cols[type].tabs || false;
        if(tabs){
            var tt,i,j,k,default_checked=0,
                tmp = '<div class="cms-jqgrid-tabs ui-tabs ui-helper-clearfix">';
                tmp += '<ul class="ui-tabs-nav ui-helper-clearfix">';
            for(i=0,l=tabs.length;i<l;i++){
                if(tabs[i].checked){
                    default_checked = i;
                }
            }
            for(i=0,l=tabs.length;i<l;i++){
                if(!tabs[i].title){
                    tt=[];
                    j=0;
                    for(j in tabs[i].cols){
                        k=0;
                        for(k in colModel){
                            if(tabs[i].cols[j]==colModel[k].name){
                                tt[tt.length] = colNames[k];
                            }
                        }
                    }
                    tabs[i].title = tt.join(', ');
                }
                
                if(i===default_checked){               
                    tmp += '<li class="ui-state-default ui-corner-top ui-state-active"><a href="#'+i+'">'+tabs[i].title+'</a></li>';
                    
                }else{       
                    for(j in tabs[i].cols){
                        k=0;
                        for(k in colModel){
                            if(tabs[i].cols[j]==colModel[k].name){
                                colModel[k].hidden = true;
                            }
                        }
                    }                  
                    tmp += '<li class="ui-state-default ui-corner-top"><a href="#'+i+'">'+tabs[i].title+'</a></li>';
                }                
            }
            tmp += '<li class="ui-state-default ui-corner-top"><a href="#'+i+'">View All</a></li>';
            tmp += '</ul></div>';
            jg.before(tmp);
            jg.prev(".cms-jqgrid-tabs").find("a").click(function (){
                var nav = $(this).parents(".ui-tabs-nav"),
                    len = $("li",nav).length,
                    cur = $("li",nav).index($("li.ui-state-active",nav)),               
                    idx = $("a",nav).index(this);
                if(idx+1 == len){
                    for(i in colModel){
                        jg.jqGrid('showCol',colModel[i].name);
                    }
                }else if(cur != idx){
                    for(i in tabs){
                        for(j in tabs[i].cols)
                        jg.jqGrid('hideCol',tabs[i].cols[j]);
                    }
                    for(i in tabs[idx].cols){
                        jg.jqGrid('showCol',tabs[idx].cols[i]);
                    }                    
                }
			
                $("li.ui-state-active",nav).removeClass("ui-state-active");
                $(this).parent().addClass("ui-state-active");
                return false;
            });
            var reset_width = function (){
                var cms_jg = $(this).parents(".cms-jqgrid"),
                    w = cms_jg.width()-2;                                        
                $(".ui-jqgrid", cms_jg).width(w);
                $(".ui-jqgrid-view", cms_jg).width(w);
                $(".ui-jqgrid-hdiv", cms_jg).width(w);
                $(".ui-jqgrid-bdiv", cms_jg).width(w);                    
                $(".ui-jqgrid-pager", cms_jg).width(w);
            };
            if(!!jg_options.loadComplete){
                var tmp = jg_options.loadComplete;
                jg_options.loadComplete = function (){
                    reset_width.apply(this);
                    tmp.apply(this);
                };
            }else{
                jg_options.loadComplete = reset_width;
            }
        }      
		
		
        jg.jqGrid(jg_options).navGrid('#result-pager1',{edit:false,add:false,del:false}).ready(TVB.Pdes.Mod.extendJqgrid);
		


    },
    
    initTaskList : function () {
        var listUrl, colNames, colModel, multiselect;
    
        listUrl = TVB.Pdes.Config.URL.GET_TASK_LIST;
        listUrl += listUrl.match(/\?/) ? '&' : '?';
        
        colNames = ['Action Type', 'Item ID', 'Item Type', 'Programme Title', 'Item Title', 'Record Status','Action Date/Time','Action Buttons'];
        colModel = [
            {name:'Action_Type',index:'action', width:100, sortable:false},
            {name:'Item ID',index:'id', width:65, sortable:false},
            {name:'Item_Type',index:'item', width:100, sortable:false},
            {name:'Programme_Title',index:'programme_title', width:155, sortable:false},
            {name:'Item_Title',index:'title', width:155, sortable:false},
            {name:'Status',index:'status', width:104, align:"left", sortable:false},
            {name:'Time',index:'time', width:95, align:"left", sortable:false},		
            {name:'op',index:'op', width:130, sortable:false}		
        ];
        multiselect = false;
        
        $("#task-list1").jqGrid({
           	url: listUrl + "date=" + $("#task-date1").html() + '&'  + ((window.location.search)?window.location.search.substr(1):''),
        	datatype : "json",
           	colNames : colNames,
           	colModel : colModel,
           	rowNum : 10,
           	rowList : [10],
           	imgpath : '',
           	pager : jQuery('#task-pager1'),
           	sortname : 'time',
            viewrecords : true,
            sortorder : "desc",
            height : 'auto',
            caption : "",
            multiselect : multiselect
        }).navGrid('#task-pager1',{edit:false,add:false,del:false}).ready(TVB.Pdes.Mod.extendJqgrid);        
        
        
        $("#task-list2").jqGrid({
           	url: listUrl + "date=" + $("#task-date2").html() + '&'  + ((window.location.search)?window.location.search.substr(1):''),
        	datatype : "json",
           	colNames : colNames,
           	colModel : colModel,
           	rowNum : 10,
           	rowList : [10],
           	imgpath : '',
           	pager : jQuery('#task-pager2'),
           	sortname : 'time',
            viewrecords : true,
            sortorder : "desc",
            height : 'auto',
            caption : "",
            multiselect : multiselect
        }).navGrid('#task-pager2',{edit:false,add:false,del:false}).ready(TVB.Pdes.Mod.extendJqgrid);
    },

    initMisList: function () {

        var listUrl = TVB.Pdes.Config.URL.GET_MIS_LIST;
        listUrl += listUrl.match(/\?/) ? '&' : '?' + ((window.location.search)?window.location.search.substr(1):'');

        var colNames = ['PDES ID', 'Type', 'Status', 'Message', 'Modified At', 'Modified By', 'Action Buttons'];
        var colModel = [
            {'name':'id', 'index':'id', 'width':'65'},
            {'name':'type', 'index':'type', 'width':'80'},
            {'name':'status', 'index':'status', 'width':'80'},
            {'name':'message', 'index':'message', 'width':'315'},
            {'name':'modified_at', 'index':'modified_at', 'width':'150'},
            {'name':'modified_by', 'index':'modified_by', 'width':'150'},
            {'name':'op', 'index':'op', 'width':'115', 'sortable':false,}
        ];

        $("#mis-grid-list").jqGrid({
           	url: listUrl,
        	datatype : "json",
           	colNames : colNames,
           	colModel : colModel,
           	rowNum : 20,
           	rowList : [10,20,30,40,50],
           	imgpath : '',
           	pager : jQuery('#mis-grid-pager'),
           	sortname : 'modified_at',
            viewrecords : true,
            sortorder : "desc",
            height : 'auto',
            caption : "",
            multiselect : false
        }).navGrid('#mis-grid-pager',{edit:false,add:false,del:false}).ready(TVB.Pdes.Mod.extendJqgrid);

        $('#mis-list form[name="mis-filter"]').submit(function (e) {
            e.preventDefault();
            var type = this.pdes_type.value;
            var begin = this.modified_at_begin.value;
            var end = this.modified_at_end.value;
		//	var pdes_id = this.pdes_id.value;
            var arrSearch = [];
            type !== '' && arrSearch.push('searchField[]=pdes_type&searchOper[]=eq&searchString[]=' + type);
            begin !== '' && arrSearch.push('searchField[]=modified_at_begin&searchOper[]=eq&searchString[]=' + begin);
            end !== '' && arrSearch.push('searchField[]=modified_at_end&searchOper[]=eq&searchString[]=' + end);
		//	pdes_id !== '' && arrSearch.push('searchField[]=pdes_id&searchOper[]=eq&searchString[]=' + pdes_id);
            $('#mis-grid-list').jqGrid('setGridParam',{url: listUrl + '&' + arrSearch.join('&'),page:1}).trigger("reloadGrid");
        });

    },
    
    initAutoPublishList: function () {

        var listUrl = TVB.Pdes.Config.URL.GET_AUTOPUBLISH_LIST;
        //listUrl += listUrl.match(/\?/) ? '&' : '?' + ((window.location.search)?window.location.search.substr(1):'');

        var colNames = ['Programme ID', 'Programme Title', 'Status', 'Publish time', 'Expire Time', 'Action Buttons'];
        var colModel = [
            {'name':'id', 'index':'id', 'width':'105'},
            {'name':'title', 'index':'title', 'width':'270'},
            {'name':'status', 'index':'status', 'width':'100'},
            {'name':'publish_time', 'index':'publish_time', 'width':'150'},
            {'name':'expire_time', 'index':'expire_time', 'width':'150'},
            {'name':'op', 'index':'op', 'width':'180', 'sortable':false,}
        ];

        $("#autopublish-list1").jqGrid({
           	url: listUrl,
        	datatype : "json",
           	colNames : colNames,
           	colModel : colModel,
           	rowNum : 20,
           	rowList : [10,20,30,40,50],
           	imgpath : '',
           	pager : jQuery('#autopublish-pager1'),
           	sortname : 'modified_at',
            viewrecords : true,
            sortorder : "desc",
            height : 'auto',
            caption : "",
            multiselect : false
        }).navGrid('#autopublish-pager1',{edit:false,add:false,del:false}).ready(TVB.Pdes.Mod.extendJqgrid);

    },
	
	initNameList: function () {

        var listUrl = TVB.Pdes.Config.URL.GET_NAME_LIST;
        listUrl += listUrl.match(/\?/) ? '&' : '?' + ((window.location.search)?window.location.search.substr(1):'');

        var colNames = ['ID', 'Master', '姓', '名', 'Last', 'First 1', 'First 2','Other','Remark','Action  Buttons','Action  Buttons'];
        var colModel = [
            {'name':'id', 'index':'id', 'width':'80'},
            {'name':'type', 'index':'type', 'width':'80'},
            {'name':'status', 'index':'status', 'width':'80'},
            {'name':'message', 'index':'message', 'width':'80'},
            {'name':'modified_at', 'index':'modified_at', 'width':'90'},
            {'name':'modified_by', 'index':'modified_by', 'width':'80'},
			{'name':'modified_by', 'index':'modified_by', 'width':'90'},
			{'name':'modified_by', 'index':'modified_by', 'width':'87'},
			{'name':'modified_by', 'index':'modified_by', 'width':'90'},
            {'name':'op', 'index':'op', 'width':'100', 'sortable':false,},
			{'name':'op1', 'index':'op1', 'width':'100', 'sortable':false,}
        ];

        $("#name-grid-list").jqGrid({
           	url: listUrl,
        	datatype : "json",
           	colNames : colNames,
           	colModel : colModel,
           	rowNum : 20,
           	rowList : [10,20,30,40,50],
           	imgpath : '',
           	pager : jQuery('#name-grid-pager'),
           	sortname : 'modified_at',
            viewrecords : true,
            sortorder : "asc",
            height : 'auto',
            caption : "",
            multiselect : false
        }).navGrid('#name-grid-pager',{edit:false,add:false,del:false}).ready(TVB.Pdes.Mod.extendJqgrid);

        $('#mis-list form[name="mis-filter"]').submit(function (e) {
            e.preventDefault();
            var type = this.pdes_type.value;
            var begin = this.modified_at_begin.value;
            var end = this.modified_at_end.value;
            var arrSearch = [];
            type !== '' && arrSearch.push('searchField[]=pdes_type&searchOper[]=eq&searchString[]=' + type);
            begin !== '' && arrSearch.push('searchField[]=modified_at_begin&searchOper[]=eq&searchString[]=' + begin);
            end !== '' && arrSearch.push('searchField[]=modified_at_end&searchOper[]=eq&searchString[]=' + end);
            $('#name-grid-list').jqGrid('setGridParam',{url: listUrl + '&' + arrSearch.join('&')}).trigger("reloadGrid");
        });

    },
    
    initProgrammeIdAutoComplete : function () {
        TVB.util.once(TVB.Pdes.Mod.setAutoCompleteDefaults);     
        if( $('#programme_title_en').attr('autocomplete') != 'off' || $('#programme_id').attr('type') != 'hidden' ){
            return false;
        }
        
        var arrId = ['programme_path', 'programme_title_cn', 'programme_title_en', 'programme_id', 'programme_eps'];
        var reset = function (exceptionId) {
            var len = arrId.length;
            for (var i = 0; i < len; i += 1) {
                if (exceptionId !== arrId[i]) {
                    $('#' + arrId[i]).val('');
                }
            }
        };

        //extended by simon
        var returnHandler = function (data, input) {
            var len = arrId.length,
                key,
                id = input.id;
            for (var i = 0; i < len; i += 1) {
                if (id !== arrId[i]) {
                    key = arrId[i].substr(10);
                    $('#' + arrId[i]).val(data[key]);
                }
            }
        };
        var options = {'returnHandler': returnHandler};
      
        var url = TVB.Pdes.Config.URL.GET_PROGRAMME;
        url += url.match(/\?/) ? '&' : '?';
    	$("#programme_title_en").autocomplete(url + 'type=title_en', options);
    	$("#programme_title_cn").autocomplete(url + 'type=title_cn', options);
    	$("#programme_path").autocomplete(url + 'type=path', options);
        $("#programme_title_en, #programme_title_cn, #programme_path").keyup( function (event){
            if ( !TVB.util.isControlKey(event.keyCode) ) {
                reset(this.id);
            }
        });

    },

    initCastLanguageId: function () {
        var $languageId = $('#cast form input[name="language_id"]'),
            $nameWrapper = $('#cast form .form-item.name .grid-r');
        $('#cast form input[name="alphabets"]').click(function () {
            if (this.checked) {
                $languageId.val(1);
                $nameWrapper.removeClass('en');
            } else {
                $languageId.val(2);
                $nameWrapper.addClass('en');
            }
        });
    },
    
    initCountryList: function () {
        $('#country-list').click( function (event){
            if(this.value.toUpperCase() == 'ALL'){
                for(var i=1,l=this.length; i<l; i++){
                    this.options[i].selected = false;
                }
            }
        });
    },
    
    initPopFolder: function () {
        var PopFolders = null;
        var PopFolder = null;
        var oFolders = null;
        var oFolder = null;
        var get_folders_url = TVB.Pdes.Config.URL.GET_FOLDERS;
        get_folders_url += (get_folders_url.match(/\?/)) ? '&' : '?';
        var update_folder_url = TVB.Pdes.Config.URL.UPDATE_FOLDER;
        update_folder_url += (update_folder_url.match(/\?/)) ? '&' : '?';
        
        var watermarks = [];
        var ops = $("option", "#pop-folder .image select[name='watermark']");
        for(var i=0; i<ops.length; i++){
            watermarks[ops[i].value] = ops[i].innerHTML;
        }
        
        $("input[name='title_en'],input[name='title_cn']", "#pop-folder").attr('maxlength','255');
        
        $('a.folder-manager-btn').bind("click", function (e) {
            e.preventDefault();
            
            $("#pop-folders>div").hide();
            $("#pop-folder>div").hide();
            
            var m = $(this).attr('href').match(/#(image|video)\-(\w+)\-(\d*)/),
            _folder_item_type = m[1],
            _type = m[2],
            _id = m[3];
            list_url = get_folders_url + 'type='+_type+'&id='+_id+'&folder_item_type='+_folder_item_type;
            
            oFolders = $("#pop-folders ."+_folder_item_type);            
            $("input[name='type']", oFolders).val(_type);
            $("input[name='id']", oFolders).val(_id);
            $("input[name='_folder_item_type']", oFolders).val(_folder_item_type);
            oFolders.show();
            //oFolders.data('folders_changed', false);
            
            oFolder = $("#pop-folder ."+_folder_item_type);            
            $("input[name='type']", oFolder).val(_type);
            $("input[name='id']", oFolder).val(_id);
            $("input[name='_folder_item_type']", oFolder).val(_folder_item_type);
            oFolder.show();
            
            if (PopFolders === null) {
                PopFolders = $("#pop-folders").dialog({
                    bgiframe: true,
                    resizable: false,
                    width: 720,
                    autoOpen: false,
                    modal: true
                });
            }
            if (PopFolder === null) {
                PopFolder = $("#pop-folder").dialog({
                    bgiframe: true,
                    resizable: false,
                    width: 520,
                    autoOpen: false,
                    modal: true,
                    open: function (event, ui){
                        $("a.ui-dialog-titlebar-close", ui).removeClass("ui-state-focus");
                    }
                });
            }
            
            PopFolders.dialog('option', 'title', 'Manage Folders ');            
            
            var foldersUL = $(".folder-list", oFolders);
            
            var update_folder = function (act, data) {
            
                var url = update_folder_url+'act='+act;
                $.ajax({
                   type: "GET",
                   url: url,
                   data: data,
                   success: function (o){
                        if(!!o && o.status == '1'){
                            if(act != 'delete'){
                                PopFolder.dialog('close');
                            }
                            list_folders(true);
                        }else{
                            alert(o.msg);
                        }
                   },
                   dataType: 'json'
                });
            };
            
            var reset_folder = function (o){
                $("input[name='act']", oFolder).val(o.act);
                $("input[name='folder_id']", oFolder).val(o.folder_id);
                $("input[name='title_en']", oFolder).val(o.title_en);
                $("input[name='title_cn']", oFolder).val(o.title_cn);
                $("select[name='folder_type']", oFolder).val(o.folder_type);
                if(_folder_item_type == 'image'){
                    $("select[name='watermark']", oFolder).val(o.watermark);
                }    
            };
            
            var folders_loaded = function (o) {
                
                if(!!o && o.length){
                    var html = [];
                    for(var i=0, l=o.length; i<l; i++){
                        html[html.length] = '<li id="folder_'+o[i].id+'" class="folder-line">';
                        html[html.length] = '<span class="grid grid-'+ (_folder_item_type=='image'?'1':'0') +'">';
                        html[html.length] = o[i].title_en + ' ' + o[i].title_cn + '</span>';
                        html[html.length] = (_folder_item_type=='image'?'<span class="grid grid-2">' + watermarks[o[i].watermark] + '</span>':'');
                        html[html.length] = '<span class="grid grid-3">';
                        html[html.length] = '<input type="hidden" name="folder_id" value="'+o[i].id+'" />';
                        html[html.length] = '<input type="hidden" name="folder_type" value="'+o[i].folder_type+'" />';
                        html[html.length] = '<input type="hidden" name="title_en" value="'+o[i].title_en+'" />';
                        html[html.length] = '<input type="hidden" name="title_cn" value="'+o[i].title_cn+'" />';
                        html[html.length] = (_folder_item_type=='image'?'<input type="hidden" name="watermark" value="'+o[i].watermark+'" />':'');
                        html[html.length] = '  <a class="btn ui-state-default ui-corner-all edit-folder" href="#'+o[i].id+'"><span class="ui-icon ui-icon-pencil"></span>Edit</a>';
                        html[html.length] = (o[i].has_item=='0')?'  <a class="btn ui-state-default ui-corner-all delete-folder" href="#'+o[i].id+'"><span class="ui-icon ui-icon-trash"></span>Delete</a>':'';
                        html[html.length] = '</span>';
                        html[html.length] = '</li>';
                    }
                    html = html.join('');
                    
                    $("li.folder-line", foldersUL).remove();
                    foldersUL.append(html);                    
                    foldersUL.fadeIn('fast'); 
                    
                    /*foldersUL.sortable({
                        axis: 'y',
                        opacity: '0.5',
                        items: 'li.folder-line',
                        update: function (e, ui){
                            var orders = foldersUL.sortable('serialize').replace(/&?folder\[\]=/g,',').substr(1);
                            console.log(orders);
                        }
                    });*/

                    
                    $(".edit-folder", oFolders).bind("click", function (e){
                        e.preventDefault();
                        
                        oFolder.data('defaultValue', {
                            'act': 'update',
                            'folder_id': $(this).siblings("input[name='folder_id']").val(),
                            'title_en': $(this).siblings("input[name='title_en']").val(),
                            'title_cn': $(this).siblings("input[name='title_cn']").val(),
                            'folder_type': $(this).siblings("input[name='folder_type']").val(),
                            'watermark': $(this).siblings("input[name='watermark']").val()
                        });
                        reset_folder(oFolder.data('defaultValue'));
                
                        PopFolder.dialog('option', 'title', 'Edit Folder');
                        PopFolder.dialog('open');
                        
                        return false;
                    });
                    
                    $(".delete-folder", oFolders).bind("click", function (e){
                        e.preventDefault();
                        
                        if( confirm(TVB.Pdes.Config.TXT.CONFIRM_DEL) ){
                            var folder_id = this.href.replace(/.*#/,'');
                            update_folder('delete', 'id='+_id+'&type='+_type+'&folder_id='+folder_id);
                        }
                        
                        return false;
                    });
                }                
                
                PopFolders.dialog('open');
            };
            
            var list_folders = function (folders_changed){
            
                if(folders_changed){
                    foldersUL.fadeOut();
                }else{
                    foldersUL.hide();
                }                
                
                $.ajax({
                   type: "GET",
                   url: list_url,
                   cache: false,
                   success: folders_loaded,
                   dataType: "json"
                });                
                
                oFolders.data('folders_changed',folders_changed);
            };
             
            $(".add-folder", oFolders).unbind("click").bind("click", function (e){
                e.preventDefault();
                
                oFolder.data('defaultValue', {
                    'act': 'create',
                    'folder_id': '',
                    'title_en': '',
                    'title_cn': '',
                    'folder_type': '',
                    'watermark': '1'
                });
                reset_folder(oFolder.data('defaultValue'));       
                
                PopFolder.dialog('option', 'title', 'Add Folder');
                PopFolder.dialog('open');
                
                return false;
            });
            
            $("form", oFolders).bind("submit", function (e){
                e.preventDefault();                 
                return false;
            });
            $("input[name='submit']", oFolders).unbind("click").bind("click", function (e){
                e.preventDefault();                
                
                PopFolders.dialog('close');                
                
                if(oFolders.data('folders_changed')){
                    $("form[name='ane'] input[name='is_folder_update']").val("1");
                    $("form[name='ane'] input[name='update']").click();
                }
                
                return false;
            });
            $("input[type='reset']", oFolders).unbind("click").bind("click", function (e){
                e.preventDefault();                
                
                PopFolders.dialog('close');
                
                return false;
            });
            
            $("form", oFolder).unbind("submit").bind("submit", function (e){
                e.preventDefault(); 
                
                if($.trim(this.title_en.value)==='' && $.trim(this.title_cn.value)===''){
                    alert(TVB.Pdes.Config.TXT.FOLDER_NAME_REQ);
                    return false;
                }
                if(!this.folder_type.value){
                    alert(TVB.Pdes.Config.TXT.FOLDER_TYPE_REQ);
                    return false;
                }
                
                var act = (this.folder_id.value)? 'update':'create';
                var data = $(this).serialize();
                
                update_folder(act, data);
                
                return false;
            });
            $("input[type='reset']", oFolder).unbind("click").bind("click", function (e){
                e.preventDefault(); 
                reset_folder(oFolder.data('defaultValue')); 
                return false;               
            });
            
            
            list_folders();
            
            return false;
             
        });        
    },
    initDownLinks : function () {
        $('a.download').click(function (e) {
            e.preventDefault();
        });
    },
    
    initPopSync : function (){
        var oPopSync = null;
        $('input.sync').bind("click", function (e) {
            if (oPopSync === null) {
                oPopSync = $("#pop-sync").dialog({
                    bgiframe: true,
                    resizable: false,
                    width: 760,
                    autoOpen: false,
                    modal: true
                });
            }
            
            oPopSync.dialog('option', 'title', 'MIS Information for XXXX');
            oPopSync.dialog('open');
        });
    },

    initBtnEditEps: function () {
    	$('#pms-ane form a.btn-edit-eps').click(function (e) {
            e.preventDefault();
            var episodeNo = $(this).parent().find('input[name="onair_episode_no"]').val();
            var arrEps = $(this).parent().find('input[name="eps"]').val().split(',');
            if (episodeNo === '') {
                alert(TVB.Pdes.Config.TXT.PLS_INPUT_EPS);
            } else if ($.inArray(episodeNo, arrEps) === -1) {
                alert(TVB.Pdes.Config.TXT.EPS_NOT_EXIST);
            } else {
                if (confirm(TVB.Pdes.Config.TXT.CONFIRM_REDIRECTTO_EPS)) {
                    $(this).parent().find('input[name="edit_eps"]').val(1);
                    $(this).closest('form').submit();
                }
            }
    	});
    },

    initCopyrightField: function () {
        $('#pms-ane form input[name="copyright"]').change(function () {
            $copyright_owner = $(this).closest('span.grid-r').find('input[name="copyright_owner"]');
            if (this.value === 'TVB') {
                $copyright_owner.attr('disabled', 'disabled');
            } else {
                $copyright_owner.removeAttr('disabled');
            }
        });
    },

    initAddCast: function () {
        var url = 'services/add_cast.php';
        $('#pop-cast form').submit(function (e) {
            e.preventDefault();
            if(!$.trim($('input[name=master_name]',this).val())){
                return false;
            }
            var submit_btn = $('input[type=submit]',this)[0];
            submit_btn.disabled = true;
            var data = $(this).serialize();
			data = data + "&programme_id=" + $("input[name=programme_id]").val();

            var $input = $('#pop-cast').data('bandedInput', $input);
            $.post(url, data, function (obj) {
                submit_btn.disabled = false;
                if (obj.status == 1) {
                    $input.val(obj.data.name);
                    $input.parent().find('input.id').val(obj.data.id);
                    $input.parent().find('a.add').trigger('click');
                    $('#pop-cast form').get(0).reset();
                    $('#pop-cast').dialog('close');
                } else {
                    alert(obj.msg);
                }
            }, 'json');
        });
    },

    initEpsInfo: function () {
        var url = TVB.Pdes.Config.URL.GET_EPISODE;
        url += (url.match(/\?/)) ? '&' : '?';
        var updateDateTime = function (arrPublish, arrExpire) {
            $('input[name="publish_datetime[]"]').each(function (i) {
                this.value = arrPublish[i];
            });
            $('input[name="expire_datetime[]"]').each(function (i) {
                this.value = arrExpire[i];
            });
        };
        var getEpsInfo = function () {
            var pid = $('#programme_id').val();
            var eps_no = $('#onair_episode_no').val();
            var arrEps = $('#programme_eps').val().split(',');
            if (eps_no !== '' && $.inArray(eps_no, arrEps) !== -1 && pid !== '') {
                $.getJSON(url, {'pid': pid, 'q': eps_no, 'type': 'eps_no', 't': (new Date()).valueOf()}, function (data){
                    if (data.eps_no == eps_no) {
                        updateDateTime(data.publish_datetime, data.expire_datetime);
                    }
                });
            } else {
                updateDateTime(['', ''], ['', '']);
            }
        };
        $('#onair_episode_no').keyup(getEpsInfo);
        $('#programme_title_en').change(getEpsInfo);
    },
    
    checkProgrammeAutoPublish : function () {
        var oPremium = $("input[name='auto_publish']"),
            oPremItem0 = $("#auto_publish-0"),
            oPremItem1 = $("#auto_publish-1"),
            oPremAutoPublish = oPremium.parents("fieldset").siblings("fieldset.auto_publish");
            
        TVB.Pdes.oValidation.rules["auto_publish_start_datetime[]"] = {};
        TVB.Pdes.oValidation.rules["auto_publish_end_datetime[]"] = {};
        
        var check = function (e){
            if($("input[name='auto_publish']:checked").val() == 1){
               // TVB.Pdes.oValidation.rules["premium_items[]"].required = true;
                TVB.Pdes.oValidation.rules.premium_auto_publish.required = true;
                oPremAutoPublish.show();
                if(oPremItem0.attr("checked")){
                    TVB.Pdes.oValidation.rules["auto_publish_start_datetime[]"].required = true;
                    TVB.Pdes.oValidation.rules["auto_publish_end_datetime[]"].required = true;
                    oPremAutoPublish.show();
                }else{
                    TVB.Pdes.oValidation.rules["auto_publish_start_datetime[]"].required = false;
                    TVB.Pdes.oValidation.rules["auto_publish_end_datetime[]"].required = false;
                    oPremAutoPublish.hide();
                }
            }else{
				TVB.Pdes.oValidation.rules["auto_publish_start_datetime[]"].required = false;
				TVB.Pdes.oValidation.rules["auto_publish_end_datetime[]"].required = false;
				//TVB.Pdes.oValidation.rules["premium_items[]"].required = false;
                TVB.Pdes.oValidation.rules.premium_auto_publish.required = false;
                oPremAutoPublish.hide();
            }
        }
        
        if(!$("#programme-step2").hasClass("view")){
            check();
            oPremium.click( check );
            oPremItem0.click( check );
            oPremItem1.click( check ); 
        }       
		
		var oTitle = oPremium.parents("fieldset").find("#title"),
			oTitleEn = oPremium.parents("fieldset").find("#title_en"),
			oPremSS = oPremium.parents("fieldset").find("#premium_items_0"),
			oPremPPV = oPremium.parents("fieldset").find("#premium_items_1"),
			oPremTitle = $("#premium_title"),
			oPremTitleEn = $("#premium_title_en");
			
			
		var keyup = function () {
			var _this = $(this);
			if(oPremSS.attr('checked') || oPremPPV.attr('checked')){			
				$("#premium_" + _this.attr('name')).val(_this.val());
			}
		
			
		}
		$(oTitle).focus(function(){
			$(oTitle).bind('keyup', keyup );
		});
		$(oTitleEn).focus(function(){
			$(oTitleEn).bind('keyup', keyup );
		});
		
		
		
		var updateTitleCheck =  function (){
		
			if(oPremTitle.val() == "" && oPremTitleEn.val() == ""){
					TVB.Pdes.oValidation.rules["premium_title_en"].required = false;
					TVB.Pdes.oValidation.rules["premium_title"].required = true;				
       				
				}else{
					TVB.Pdes.oValidation.rules["premium_title"].required = (oPremTitle.val() != "");
					TVB.Pdes.oValidation.rules["premium_title_en"].required = (oPremTitleEn.val() != "");					
			}	
		}
		
		$(oPremTitle).bind('change',updateTitleCheck);
		$(oPremTitleEn).bind('change',updateTitleCheck);	
		
		var checkPrem = function(){
            var premVals = [];
			$('input[name=premium_items[]]:checked').each(function(){
				premVals.push($(this).val());																	  
			});
																			  
			
			$('input.fvars').each(function(){
				var _thisVal = $(this).val();
				var s = _thisVal.match(/("premium":".*")/i);
				if(s!=null){
					$(this).val(_thisVal.replace(s[1],'"premium":"'+premVals.join(',')+'"'));
				}
			});
			
			
			if(!oPremSS.attr('checked') && !oPremPPV.attr('checked')){
				$("fieldset.premium_key").hide();
				TVB.Pdes.oValidation.rules["premium_title"].required = false;
				TVB.Pdes.oValidation.rules["premium_title_en"].required = false;
				
			}else{
				$("fieldset.premium_key").show();
				updateTitleCheck();
			}

			if(oPremSS.attr('checked')){
				$('input[name^='+ oPremSS.val() +']').parents('.form-item').show();	
				 TVB.Pdes.oValidation.rules["subscription_publish_datetime[]"].required = true;
                  TVB.Pdes.oValidation.rules["subscription_expire_datetime[]"].required = true;
			}else{
				$('input[name^='+ oPremSS.val() +']').parents('.form-item').hide();	
				TVB.Pdes.oValidation.rules["subscription_publish_datetime[]"].required = false;
                  TVB.Pdes.oValidation.rules["subscription_expire_datetime[]"].required = false;
				
			}
			
			if(oPremPPV.attr('checked')){
				$('input[name^='+ oPremPPV.val() +']').parents('.form-item').show();
				TVB.Pdes.oValidation.rules["ppv_publish_datetime[]"].required = true;
                TVB.Pdes.oValidation.rules["ppv_expire_datetime[]"].required = true;
				
			}else{
				$('input[name^='+ oPremPPV.val() +']').parents('.form-item').hide();
				TVB.Pdes.oValidation.rules["ppv_publish_datetime[]"].required = false;
                TVB.Pdes.oValidation.rules["ppv_expire_datetime[]"].required = false;
			}
			
		}
		if(!$("#programme-step2").hasClass("view")){
			checkPrem();
			oPremSS.bind('click',checkPrem);
			oPremPPV.bind('click',checkPrem);
		}
		
		
		
	},
    checkProgrammePremium : function () {
        var oPremium = $("input[name='premium_flag']"),
            oPremItem0 = $("#premium_items_0"),
            oPremItem1 = $("#premium_items_1"),
            oPremKey = oPremium.parents("fieldset").siblings("fieldset.premium_key"),
            oPremSub = oPremium.parents("fieldset").siblings("fieldset.premium_subscription"),
            oPremPPV = oPremium.parents("fieldset").siblings("fieldset.premium_ppv");
            
        TVB.Pdes.oValidation.rules.premium_title = {"maxlength":"255"};
        TVB.Pdes.oValidation.rules.premium_title_en = {"maxlength":"255","english":true};
        TVB.Pdes.oValidation.rules["premium_items[]"] = {};
        TVB.Pdes.oValidation.rules.premium_auto_publish = {};
        TVB.Pdes.oValidation.rules["subscription_publish_datetime[]"] = {};
        TVB.Pdes.oValidation.rules["subscription_expire_datetime[]"] = {};
        TVB.Pdes.oValidation.rules.subscription_free = {};
        TVB.Pdes.oValidation.rules.subscription_country_allow_deny = {};
        TVB.Pdes.oValidation.rules["ppv_publish_datetime[]"] = {};
        TVB.Pdes.oValidation.rules["ppv_expire_datetime[]"] = {};
        TVB.Pdes.oValidation.rules.ppv_country_allow_deny = {};
        
        var check = function (e){
            var title = $("#title").val(),
                title_en = $("#title_en").val(),
                premium_title = $("#premium_title").val() || title,
                premium_title_en = $("#premium_title_en").val() || title_en;
            if(e){    
                $("#premium_title").val(premium_title);
                $("#premium_title_en").val(premium_title_en);
            }
            if($("input[name='premium_flag']:checked").val() == 1){
                TVB.Pdes.oValidation.rules["premium_items[]"].required = true;
                TVB.Pdes.oValidation.rules.premium_auto_publish.required = true;
                oPremKey.show();
				
				
                if(oPremItem0.attr("checked")){
                    TVB.Pdes.oValidation.rules["subscription_publish_datetime[]"].required = true;
                    TVB.Pdes.oValidation.rules["subscription_expire_datetime[]"].required = true;
                    TVB.Pdes.oValidation.rules.subscription_free.required = true;
                    TVB.Pdes.oValidation.rules.subscription_country_allow_deny.required = true;
                    oPremSub.show();
                }else{
                    TVB.Pdes.oValidation.rules["subscription_publish_datetime[]"].required = false;
                    TVB.Pdes.oValidation.rules["subscription_expire_datetime[]"].required = false;
                    TVB.Pdes.oValidation.rules.subscription_free.required = false;
                    TVB.Pdes.oValidation.rules.subscription_country_allow_deny.required = false;
                    oPremSub.hide();
                }
                if(oPremItem1.attr("checked")){
                    TVB.Pdes.oValidation.rules["ppv_publish_datetime[]"].required = true;
                    TVB.Pdes.oValidation.rules["ppv_expire_datetime[]"].required = true;
                    TVB.Pdes.oValidation.rules.ppv_country_allow_deny.required = true;
                    oPremPPV.show();
                }else{
                    TVB.Pdes.oValidation.rules["ppv_publish_datetime[]"].required = false;
                    TVB.Pdes.oValidation.rules["ppv_expire_datetime[]"].required = false;
                    TVB.Pdes.oValidation.rules.ppv_country_allow_deny.required = false;
                    oPremPPV.hide();
                }
            }else{
                TVB.Pdes.oValidation.rules["premium_items[]"].required = false;
                TVB.Pdes.oValidation.rules.premium_auto_publish.required = false;
                oPremKey.hide();
                oPremSub.hide();
                oPremPPV.hide();
            }
        }
       
        if(!$("#programme-step2").hasClass("view")){
		
            check();
            oPremium.click( check );
            oPremItem0.click( check );
            oPremItem1.click( check ); 
        }    
    },
    
    checkProgrammePremiumItems : function () {
		
        var oPremium = $("input[name='premium_flag']"),
			oPremItem0 = $("#premium_items_0"),
            oPremItem1 = $("#premium_items_1"),
            oPremSub = oPremItem0.parents("fieldset").siblings("fieldset.premium_subscription"),
            oPremPPV = oPremItem0.parents("fieldset").siblings("fieldset.premium_ppv");
            
        TVB.Pdes.oValidation.rules["subscription_publish_datetime[]"] = {};
        TVB.Pdes.oValidation.rules["subscription_expire_datetime[]"] = {};
        TVB.Pdes.oValidation.rules.subscription_free = {};
        TVB.Pdes.oValidation.rules.subscription_country_allow_deny = {};
        TVB.Pdes.oValidation.rules["ppv_publish_datetime[]"] = {};
        TVB.Pdes.oValidation.rules["ppv_expire_datetime[]"] = {};
        TVB.Pdes.oValidation.rules.ppv_country_allow_deny = {};
        var check = function (){
            if(oPremItem0.attr("checked")){
                TVB.Pdes.oValidation.rules["subscription_publish_datetime[]"].required = true;
                TVB.Pdes.oValidation.rules["subscription_expire_datetime[]"].required = true;
                TVB.Pdes.oValidation.rules.subscription_free.required = true;
                TVB.Pdes.oValidation.rules.subscription_country_allow_deny.required = true;
                oPremSub.show();
            }else{
                TVB.Pdes.oValidation.rules["subscription_publish_datetime[]"].required = false;
                TVB.Pdes.oValidation.rules["subscription_expire_datetime[]"].required = false;
                TVB.Pdes.oValidation.rules.subscription_free.required = false;
                TVB.Pdes.oValidation.rules.subscription_country_allow_deny.required = false;
                oPremSub.hide();
            }
            if(oPremItem1.attr("checked")){
                TVB.Pdes.oValidation.rules["ppv_publish_datetime[]"].required = true;
                TVB.Pdes.oValidation.rules["ppv_expire_datetime[]"].required = true;
                TVB.Pdes.oValidation.rules.ppv_country_allow_deny.required = true;
                oPremPPV.show();
            }else{
                TVB.Pdes.oValidation.rules["ppv_publish_datetime[]"].required = false;
                TVB.Pdes.oValidation.rules["ppv_expire_datetime[]"].required = false;
                TVB.Pdes.oValidation.rules.ppv_country_allow_deny.required = false;
                oPremPPV.hide();
            }
			if(oPremItem0.attr("checked") || oPremItem1.attr("checked") ){
				oPremium.eq(0).attr("checked","checked");	
			}else{
				//oPremium.eq(1).attr("checked","checked");
			}
        }
		
		var premiunFlagCheck = function () {
			if($("input[name='premium_flag']:checked").val() == 0){
				oPremItem0.attr("checked","");
				oPremItem1.attr("checked","");
				check();
			}
			
		}
        
        if(!$("#chapter-marking").hasClass("view")){
            check();
			oPremium.click( premiunFlagCheck );
            oPremItem0.click( check );
            oPremItem1.click( check ); 
        }               
    }

};

(function () {
    var filter = TVB.util.scriptFilter,
        Mod = TVB.Pdes.Mod;

    TVB.Pdes.oParam = function () {
        var o = {};
        window.location.search.replace(/([^?=&]+)=([^&]*)/g, function (m, key, value) {
            o[key] = value;
        });
        return o;
    }();

    /* initialize components */
    if (TVB.Pdes.oParam.act && TVB.Pdes.oParam.act !== 'view') {
        TVB.Cms.uiInit(document);
    } else {
        TVB.Cms.uiInit(document);
    }


    filter({'ids': ['programme-step1']},Mod.initCreateProgramme);
    filter({'ids': ['programme-step2']},Mod.initAddCpl);
    filter({'ids': ['chapter-marking', 'video', 'image']}, Mod.initDownLinks);
    filter({'ids': ['chapter-marking', 'image']}, Mod.initBtnEditEps);
    filter({'ids': ['chapter-marking', 'image']}, Mod.initCopyrightField);
    filter({'ids': ['chapter-marking', 'image']}, Mod.initAddCast);

    //commentted while combine video with chapter-marking
    //filter({'ids': ['chapter-marking']}, Mod.initChangeVd);

    filter({'ids': ['chapter-marking']}, Mod.initChapterMarking);
    filter({
        'ids': ['programme-step2', 'episode-step2', 'chapter-marking', 'address', 'recipe', 'award', 'song', 'biography', 'video', 'image']
    }, Mod.initGlobalNameInput);
    filter({'ids': ['programme-step2', 'episode-step2', 'chapter-marking', 'cast', 'video', 'image']}, Mod.initEditableList);
    filter({'ids': ['programe-category-selector']}, Mod.initLoadProgrammeSubCat);
    filter({'ids': ['cuisine-category-selector']}, Mod.initLoadCuisineSubCat);
    filter({'ids': ['country_autocomplete', 'province_state_autocomplete']}, Mod.initLocationAutoComplete);
    filter({'ids': ['pms-ane']}, Mod.initBackButton);
    filter({'ids': ['pms-ane', 'login']}, Mod.initValidation);
    filter({'ids': ['result-list']}, Mod.initResultList);
    filter({'ids': ['task-list']}, Mod.initTaskList);

    //commented because mam api is not ready
    //filter({'ids': ['programme-step1']}, Mod.initMamAutoFill);

    filter({'ids': ['result-list', 'task-list']}, Mod.saveUrlInSession);
    filter({'ids': ['programme_title_en']}, Mod.initProgrammeIdAutoComplete);
    filter({'ids': ['programme-step2', 'episode-step2', 'cast']}, Mod.initRedCallers);
    filter({'ids': ['pop-find']}, Mod.initPopFind);
    filter({'ids': ['top-clock']}, Mod.initTopClock);
    filter({'ids': ['cast']}, Mod.initCastLanguageId);
    filter({'ids': ['country-list']}, Mod.initCountryList);
    filter({'ids': ['pop-folder']}, Mod.initPopFolder);
    filter({'ids': ['pop-sync']}, Mod.initPopSync);

    filter({
        'ids': ['address','recipe','song','biography','award','product','qa','general_info','pageant']
    }, Mod.initEpsInfo);

    filter({'ids': ['mis-list']}, Mod.initMisList);
    
    filter({'ids': ['autopublish-list']}, Mod.initAutoPublishList);
	
	filter({'ids': ['name-list']}, Mod.initNameList);
	
	filter({'ids': ['programme-step2']},Mod.checkProgrammePremium);
	filter({'ids': ['programme-step2']},Mod.checkProgrammeAutoPublish);
	filter({'ids': ['chapter-marking']},Mod.checkProgrammePremiumItems);
})();
/*
TVB.util.namespace('TVB.Pdes.CFG');
TVB.Pdes.CFG = {
    jgw : { //column's width in jqgrid
        ID : '65',
        Date : '100'
    }
};
var JGW = TVB.Pdes.CFG.jgw;
*/
